Example usage for java.lang Thread sleep

List of usage examples for java.lang Thread sleep

Introduction

In this page you can find the example usage for java.lang Thread sleep.

Prototype

public static native void sleep(long millis) throws InterruptedException;

Source Link

Document

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

Usage

From source file:eu.optimis.elasticityengine.EETester.java

public static void main(String[] args) throws IOException, InterruptedException {

    if (args.length != 1) {
        printUsage();//from w w w. j a  v  a2s  .c om
        System.exit(-1);
    }

    Logger log = Logger.getLogger(ElasticityEngineImpl.class);
    System.out.println("Testing Elasticity Engine");
    System.out.println("One instance per 100 users expected, starting at 1");

    ElasticityEngine eEngine = new ElasticityEngineImpl();
    String manifest = Util.getManifest(args[0]);
    String serviceID = "EETester"; // TODO parse somehow?
    String sp = "SP_Add";
    boolean LowRiskMode;

    ElasticityCallback callback = new CallbackPrinter();
    if ("true".equals(System.getProperty("lowrisk"))) {
        System.out.println("USING Low Risk Mode");
        LowRiskMode = true;
    } else {
        System.out.println("USING Low cost Mode");
        LowRiskMode = false;
    }
    eEngine.startElasticity(serviceID, manifest, LowRiskMode, sp);

    //Call a test-specific method which only returns when we got the -2 recommendation, and the test should then be done.
    ((CallbackPrinter) callback).awaitLoad(1);
    System.out.println("\nTest done, exiting");
    Thread.sleep(500);
}

From source file:de.zazaz.iot.bosch.indego.App.java

public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(BASE_URL_PUSHWOOSH + "registerDevice");
    String jsonPost = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"push_token\":\"124692134091\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"," //
            + "     \"timezone\":3600," //
            + "     \"device_type\":3" //
            + "  }" //
            + "}";
    httpPost.setEntity(new StringEntity(jsonPost, ContentType.APPLICATION_JSON));
    CloseableHttpResponse response = httpClient.execute(httpPost);

    System.out.println(response.getStatusLine());
    Header[] headers = response.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i].getName() + ": " + headers[i].getValue());
    }// w w  w. ja va  2  s . co m
    HttpEntity entity = response.getEntity();
    String contents = EntityUtils.toString(entity);
    System.out.println(contents);

    Thread.sleep(5000);

    HttpPost httpGet = new HttpPost(BASE_URL_PUSHWOOSH + "checkMessage");
    String jsonGet = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"" //
            + "  }" //
            + "}";
    httpGet.setEntity(new StringEntity(jsonGet, ContentType.APPLICATION_JSON));
    httpClient.execute(httpGet);

    response.close();
}

From source file:org.wso2.carbon.sample.http.Http.java

public static void main(String args[]) {
    log.info("Starting WSO2 Http Client");
    HttpUtil.setTrustStoreParams();/*from ww w  .  j av a 2  s.  c  o m*/
    String url = args[0];
    String username = args[1];
    String password = args[2];
    String sampleNumber = args[3];
    String filePath = args[4];
    HttpClient httpClient = new SystemDefaultHttpClient();
    try {
        HttpPost method = new HttpPost(url);
        filePath = HttpUtil.getMessageFilePath(sampleNumber, filePath, url);
        readMsg(filePath);
        for (String message : messagesList) {
            StringEntity entity = new StringEntity(message);
            log.info("Sending message:");
            log.info(message + "\n");
            method.setEntity(entity);
            if (url.startsWith("https")) {
                processAuthentication(method, username, password);
            }
            httpClient.execute(method).getEntity().getContent().close();
        }
        Thread.sleep(500); // Waiting time for the message to be sent
    } catch (Throwable t) {
        log.error("Error when sending the messages", t);
    }
}

From source file:example.springdata.redis.sentinel.RedisSentinelApplicationConfig.java

public static void main(String[] args) throws Exception {

    ApplicationContext context = SpringApplication.run(RedisSentinelApplicationConfig.class, args);

    RedisConnectionFactory factory = context.getBean(RedisConnectionFactory.class);

    StringRedisTemplate template = new StringRedisTemplate();
    template.setConnectionFactory(factory);
    template.afterPropertiesSet();/*  ww w .  j  a v  a 2  s .  c o  m*/

    template.opsForValue().set("loop-forever", "0");

    StopWatch stopWatch = new StopWatch();

    while (true) {

        try {
            String value = "IT:= " + template.opsForValue().increment("loop-forever", 1);
            printBackFromErrorStateInfoIfStopWatchIsRunning(stopWatch);
            System.out.println(value);
        } catch (RuntimeException e) {
            System.err.println(e.getCause().getMessage());
            startStopWatchIfNotRunning(stopWatch);
        }

        Thread.sleep(1000);
    }
}

From source file:com.yahoo.ads.pb.mttf.PistachiosMTTFTest.java

public static void main(String[] args) {
    PistachiosClient client;//from w ww  . j a  v  a 2  s.  c o m
    try {
        client = new PistachiosClient();
    } catch (Exception e) {
        logger.info("error creating client", e);
        return;
    }
    Random rand = new Random();

    while (true) {
        try {
            long id = rand.nextLong();
            String value = InetAddress.getLocalHost().getHostName() + rand.nextInt();
            client.store(0, id, value.getBytes());
            for (int i = 0; i < 30; i++) {
                byte[] clientValue = client.lookup(0, id);
                String remoteValue = new String(clientValue);
                if (Arrays.equals(value.getBytes(), clientValue)
                        || !remoteValue.contains(InetAddress.getLocalHost().getHostName())) {
                    logger.debug("succeeded checking id {} value {}", id, value);
                } else {
                    logger.error("failed checking id {} value {} != {}", id, value, new String(clientValue));
                    System.exit(0);
                }
                Thread.sleep(100);
            }
        } catch (Exception e) {
            System.out.println("error testing" + e);
            System.exit(0);
        }
    }
}

From source file:gr.cslab.Metric_test.java

public static void main(String[] args) throws InterruptedException {

    readArgs(Arrays.asList(args));
    loadHostFile();//  w  ww  .  jav a 2s .  c  o  m
    JSONArray inJson = file2Json(metricsFile);
    loadJsonMetrics(inJson);
    if (hostsFile != null) {
        //TODO: read hosts file
    }

    connectToHosts();

    //if the list arg was given, only list the available names and exit
    if (list) {
        list();
        System.exit(0);
    }

    for (;;) {
        reportAll();
        Thread.sleep(interval * 1000);
    }

}

From source file:camera.Camera.java

/**
 * @param args the command line arguments
 *//*from  ww  w .  ja v a 2s .c  o m*/
public static void main(String[] args) throws Exception {
    System.out.println("start compass.");
    //   Compass c = new Compass();
    //   c.start();
    System.out.println("start camera.");
    Camera cam = new Camera();
    cam.snapshot();
    // regelmssig zu festen Sekunden Foto schiessen. Thread.
    int phase;
    int lastPhase = -1;
    while (true) {
        Calendar cal = new GregorianCalendar();
        int stunde = cal.get(Calendar.HOUR_OF_DAY);
        int STUNDE_VON = 7;
        int STUNDE_BIS = 23;
        if ((stunde < STUNDE_VON) || (stunde > STUNDE_BIS)) {
            Thread.sleep(1000);
            continue;
        }
        // regelmssig Fotos
        int sekunde = cal.get(Calendar.SECOND);
        phase = sekunde / 10; // alle 10 sekunden wechsel  jede volle zehner wechselt
        //phase = phase % 4; // 4 phasen wenn ma unterteilen wollte

        if (phase == lastPhase) {
            //    Thread.sleep(300);
            //      continue;
        }
        lastPhase = phase;
        // zeit fr ein Foto.
        cam.snapshot();

    }
}

From source file:kafka.examples.producer.BasicProducerExample.java

public static void main(String[] args) {
    ArgumentParser parser = argParser();

    try {//  ww  w. j  a va 2 s  .  com
        Namespace res = parser.parseArgs(args);

        /* parse args */
        String brokerList = res.getString("bootstrap.servers");
        String topic = res.getString("topic");
        Boolean syncSend = res.getBoolean("syncsend");
        long noOfMessages = res.getLong("messages");
        long delay = res.getLong("delay");
        String messageType = res.getString("messagetype");

        Properties producerConfig = new Properties();
        producerConfig.put("bootstrap.servers", brokerList);
        producerConfig.put("client.id", "basic-producer");
        producerConfig.put("acks", "all");
        producerConfig.put("retries", "3");
        producerConfig.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.ByteArraySerializer");
        producerConfig.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.ByteArraySerializer");

        SimpleProducer<byte[], byte[]> producer = new SimpleProducer<>(producerConfig, syncSend);

        for (int i = 0; i < noOfMessages; i++) {
            producer.send(topic, getKey(i), getEvent(messageType, i));
            try {
                Thread.sleep(delay);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        producer.close();
    } catch (ArgumentParserException e) {
        if (args.length == 0) {
            parser.printHelp();
            System.exit(0);
        } else {
            parser.handleError(e);
            System.exit(1);
        }
    }

}

From source file:org.eclipse.swt.snippets.Snippet104.java

public static void main(String[] args) {
    final Display display = new Display();
    final int[] count = new int[] { 4 };
    final Image image = new Image(display, 300, 300);
    GC gc = new GC(image);
    gc.setBackground(display.getSystemColor(SWT.COLOR_CYAN));
    gc.fillRectangle(image.getBounds());
    gc.drawText("Splash Screen", 10, 10);
    gc.dispose();// w  w w  .  jav a2 s.  co  m
    final Shell splash = new Shell(SWT.ON_TOP);
    final ProgressBar bar = new ProgressBar(splash, SWT.NONE);
    bar.setMaximum(count[0]);
    Label label = new Label(splash, SWT.NONE);
    label.setImage(image);
    FormLayout layout = new FormLayout();
    splash.setLayout(layout);
    FormData labelData = new FormData();
    labelData.right = new FormAttachment(100, 0);
    labelData.bottom = new FormAttachment(100, 0);
    label.setLayoutData(labelData);
    FormData progressData = new FormData();
    progressData.left = new FormAttachment(0, 5);
    progressData.right = new FormAttachment(100, -5);
    progressData.bottom = new FormAttachment(100, -5);
    bar.setLayoutData(progressData);
    splash.pack();
    Rectangle splashRect = splash.getBounds();
    Rectangle displayRect = display.getBounds();
    int x = (displayRect.width - splashRect.width) / 2;
    int y = (displayRect.height - splashRect.height) / 2;
    splash.setLocation(x, y);
    splash.open();
    display.asyncExec(() -> {
        Shell[] shells = new Shell[count[0]];
        for (int i1 = 0; i1 < count[0]; i1++) {
            shells[i1] = new Shell(display);
            shells[i1].setSize(300, 300);
            shells[i1].addListener(SWT.Close, e -> --count[0]);
            bar.setSelection(i1 + 1);
            try {
                Thread.sleep(1000);
            } catch (Throwable e) {
            }
        }
        splash.close();
        image.dispose();
        for (int i2 = 0; i2 < count[0]; i2++) {
            shells[i2].setText("SWT Snippet 104 - " + (i2 + 1));
            shells[i2].open();
        }
    });
    while (count[0] != 0) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:com.baomidou.mybatisplus.test.MybatisMapperRefreshTest.java

/**
 *  Mybatis XML //from   w w  w  .j ava2 s .c om
 */
public static void main(String[] args) throws IOException, InterruptedException {
    InputStream in = UserMapperTest.class.getClassLoader().getResourceAsStream("mysql-config.xml");
    MybatisSessionFactoryBuilder mf = new MybatisSessionFactoryBuilder();
    mf.setGlobalConfig(new GlobalConfiguration(new MySqlInjector()));
    Resource[] resource = new ClassPathResource[] { new ClassPathResource("mysql/UserMapper.xml") };
    SqlSessionFactory sessionFactory = mf.build(in);
    new MybatisMapperRefresh(resource, sessionFactory, 0, 5, true);
    boolean isReturn = false;
    SqlSession session = null;
    while (!isReturn) {
        try {
            session = sessionFactory.openSession();
            UserMapper userMapper = session.getMapper(UserMapper.class);
            userMapper.selectListRow(new Pagination(1, 10));
            resource[0].getFile().setLastModified(SystemClock.now());
            session.commit();
            session.close();
            Thread.sleep(5000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
            Thread.sleep(5000);
        }
    }
    System.exit(0);
}