Example usage for java.util.concurrent TimeUnit SECONDS

List of usage examples for java.util.concurrent TimeUnit SECONDS

Introduction

In this page you can find the example usage for java.util.concurrent TimeUnit SECONDS.

Prototype

TimeUnit SECONDS

To view the source code for java.util.concurrent TimeUnit SECONDS.

Click Source Link

Document

Time unit representing one second.

Usage

From source file:Main.java

public static void stop(ExecutorService executor) {
    try {// w w w .ja va  2 s.  c  o  m
        executor.shutdown();
        executor.awaitTermination(60, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        System.err.println("termination interrupted");
    } finally {
        if (!executor.isTerminated()) {
            System.out.println("killing non-finished tasks");
        }
        executor.shutdownNow();
    }
}

From source file:com.amazonaws.services.iot.demo.danbo.rpi.Danbo.java

public static void main(String[] args) throws Exception {
    log.debug("starting");

    // uses pin 6 for the red Led
    final Led redLed = new Led(6);
    // uses pin 26 for the green Led
    final Led greenLed = new Led(26);

    // turns the red led on initially
    redLed.on();//  w ww  .ja  va  2  s.  c o m

    // turns the green led off initially
    greenLed.off();

    // loads properties from danbo.properties file - make sure this file is
    // available on the pi's home directory
    InputStream input = new FileInputStream("/home/pi/danbo/danbo.properties");
    Properties properties = new Properties();
    properties.load(input);
    endpoint = properties.getProperty("awsiot.endpoint");
    rootCA = properties.getProperty("awsiot.rootCA");
    privateKey = properties.getProperty("awsiot.privateKey");
    certificate = properties.getProperty("awsiot.certificate");
    url = protocol + endpoint + ":" + port;

    log.debug("properties loaded");

    // turns off both eyes
    RGBLed rgbLed = new RGBLed("RGBLed1", Danbo.pinLayout1, Danbo.pinLayout2, new Color(0, 0, 0),
            new Color(0, 0, 0), 0, 100);
    new Thread(rgbLed).start();

    // resets servo to initial positon
    Servo servo = new Servo("Servo", 1);
    new Thread(servo).start();

    // gets the Pi serial number and uses it as part of the thing
    // registration name
    clientId = clientId + getSerialNumber();

    // AWS IoT things shadow topics
    updateTopic = "$aws/things/" + clientId + "/shadow/update";
    deltaTopic = "$aws/things/" + clientId + "/shadow/update/delta";
    rejectedTopic = "$aws/things/" + clientId + "/shadow/update/rejected";

    // AWS IoT controller things shadow topic (used to register new things)
    controllerUpdateTopic = "$aws/things/Controller/shadow/update";

    // defines an empty danbo shadow POJO
    final DanboShadow danboShadow = new DanboShadow();
    DanboShadow.State state = danboShadow.new State();
    final DanboShadow.State.Reported reported = state.new Reported();
    reported.setEyes("readyToBlink");
    reported.setHead("readyToMove");
    reported.setMouth("readyToSing");
    reported.setName(clientId);
    state.setReported(reported);
    danboShadow.setState(state);

    // defines an empty controller shadow POJO
    final ControllerShadow controllerShadow = new ControllerShadow();
    ControllerShadow.State controllerState = controllerShadow.new State();
    final ControllerShadow.State.Reported controllerReported = controllerState.new Reported();
    controllerReported.setThingName(clientId);
    controllerState.setReported(controllerReported);
    controllerShadow.setState(controllerState);

    try {
        log.debug("registering");

        // registers the thing (creates a new thing) by updating the
        // controller
        String message = gson.toJson(controllerShadow);
        MQTTPublisher controllerUpdatePublisher = new MQTTPublisher(controllerUpdateTopic, qos, message, url,
                clientId + "-controllerupdate" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(controllerUpdatePublisher).start();

        log.debug("registered");

        // clears the thing status (in case the thing already existed)
        Danbo.deleteStatus("initialDelete");

        // creates an MQTT subscriber to the things shadow delta topic
        // (command execution notification)
        MQTTSubscriber deltaSubscriber = new MQTTSubscriber(new DanboShadowDeltaCallback(), deltaTopic, qos,
                url, clientId + "-delta" + rand.nextInt(100000), cleanSession, rootCA, privateKey, certificate);
        new Thread(deltaSubscriber).start();

        // creates an MQTT subscriber to the things shadow error topic
        MQTTSubscriber errorSubscriber = new MQTTSubscriber(new DanboShadowRejectedCallback(), rejectedTopic,
                qos, url, clientId + "-rejected" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(errorSubscriber).start();

        // turns the red LED off
        redLed.off();

        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // turns the green LED on
                greenLed.on();

                log.debug("running publish state thread");

                int temp = -300;
                int humid = -300;

                reported.setTemperature(new Integer(temp).toString());
                reported.setHumidity(new Integer(humid).toString());

                try {
                    // reads the temperature and humidity data
                    Set<Sensor> sensors = Sensors.getSensors();
                    log.debug(sensors.size());

                    for (Sensor sensor : sensors) {
                        log.debug(sensor.getPhysicalQuantity());
                        log.debug(sensor.getValue());
                        if (sensor.getPhysicalQuantity().toString().equals("Temperature")) {
                            temp = sensor.getValue().intValue();
                        }
                        if (sensor.getPhysicalQuantity().toString().equals("Humidity")) {
                            humid = sensor.getValue().intValue();
                        }
                    }

                    log.debug("temperature: " + temp);
                    log.debug("humidity: " + humid);
                    reported.setTemperature(new Integer(temp).toString());
                    reported.setHumidity(new Integer(humid).toString());
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                try {
                    // reports current state - last temperature and humidity
                    // read
                    String message = gson.toJson(danboShadow);
                    MQTTPublisher updatePublisher = new MQTTPublisher(updateTopic, qos, message, url,
                            clientId + "-update" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                            certificate);
                    new Thread(updatePublisher).start();
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                // turns the green LED off
                greenLed.off();
            }
        }, 0, 5, TimeUnit.SECONDS); // runs this thread every 5 seconds,
        // with an initial delay of 5 seconds
    } catch (MqttException me) {
        // Display full details of any exception that occurs
        log.error("reason " + me.getReasonCode());
        log.error("msg " + me.getMessage());
        log.error("loc " + me.getLocalizedMessage());
        log.error("cause " + me.getCause());
        log.error("excep " + me);
        me.printStackTrace();
    } catch (Throwable th) {
        log.error("msg " + th.getMessage());
        log.error("loc " + th.getLocalizedMessage());
        log.error("cause " + th.getCause());
        log.error("excep " + th);
        th.printStackTrace();
    }
}

From source file:Main.java

public static Runnable createNewThread(final String name) {
    return new Runnable() {
        @Override/*from   w  ww.jav  a 2  s  .  co  m*/
        public void run() {
            try {
                System.out.println("before: " + name);
                TimeUnit.SECONDS.sleep(3);
                System.out.println("end: " + name);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
}

From source file:Main.java

public static final void shutdownAndAwaitTermination(ExecutorService executorService) {

    shutdownAndAwaitTermination(executorService, defaultTimeout, TimeUnit.SECONDS);

}

From source file:Main.java

public static void shutdown() {
    try {/*from w w  w . java2s  .c o  m*/
        pool.awaitTermination(30, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        System.err.println("Shutdown was interrupted, forcing shutdown...");
        pool.shutdownNow();
        e.printStackTrace();
    }
}

From source file:Main.java

public static void shutdown(final ExecutorService executorService) {
    executorService.shutdown();//w  w  w  . j  av  a 2 s. c o  m
    try {
        int timeToWait = 30;
        if (!executorService.awaitTermination(timeToWait, TimeUnit.SECONDS)) {
            List<Runnable> executionList = executorService.shutdownNow();
            for (Runnable runnable : executionList) {
                System.out.println("Trying to shutdown task: " + runnable);
            }
        }
        if (!executorService.awaitTermination(timeToWait, TimeUnit.SECONDS)) {
        }
    } catch (InterruptedException ex) {
        executorService.shutdownNow();
        Thread.currentThread().interrupt();
    }
}

From source file:Main.java

public static String printTime(long time, TimeUnit unit) {
    long ns = TimeUnit.NANOSECONDS.convert(time, unit);
    long us = TimeUnit.MICROSECONDS.convert(time, unit);
    long ms = TimeUnit.MILLISECONDS.convert(time, unit);
    long secs = TimeUnit.SECONDS.convert(time, unit);

    if (secs > 0)
        return secs + "s";
    if (ms > 0)
        return ms + "ms";
    if (us > 0)
        return us + " us";
    return ns + "ns";
}

From source file:Main.java

public static ExecutorService newDynamicSingleThreadedExecutor() {
    ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());
    executor.allowCoreThreadTimeOut(true);

    return executor;
}

From source file:Main.java

public static ExecutorService getThreadPoolExecutor() {
    if (executor == null) {
        executor = new ThreadPoolExecutor(2, 5, 60, TimeUnit.SECONDS, new LinkedBlockingDeque<Runnable>(3));
    }/*from   ww  w. ja  v  a 2s .  c om*/
    return executor;
}

From source file:Main.java

public static final void shutdownAndAwaitTermination(ExecutorService executorService) {
    if (executorService.isShutdown()) {
        return;/*from   ww  w .  j a v a 2 s.c om*/
    }
    executorService.shutdown();
    try {
        if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
            executorService.shutdownNow();
        }
    } catch (InterruptedException ie) {
        executorService.shutdownNow();
        Thread.currentThread().interrupt();
    }
    executorService.shutdownNow();

}