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:com.harpatec.examples.Main.java

/**
 * Load the Spring Integration Application Context
 * /*from   www.j av a2  s  . co m*/
 * @param args - command line arguments
 * @throws InterruptedException
 * @throws IOException
 * @throws JsonMappingException
 * @throws JsonGenerationException
 */
public static void main(final String... args)
        throws InterruptedException, JsonGenerationException, JsonMappingException, IOException {

    final AbstractApplicationContext context = new ClassPathXmlApplicationContext(
            "classpath:META-INF/spring/integration/*-context.xml");

    context.registerShutdownHook();

    LOGGER.debug("Dropping the collection of MessageRecords");
    MongoTemplate mongoTemplate = context.getBean(MongoTemplate.class);
    mongoTemplate.dropCollection(MessageRecord.class);
    mongoTemplate.indexOps(MessageRecord.class).ensureIndex(new Index().on("key", Order.ASCENDING).unique());
    mongoTemplate.indexOps(MessageRecord.class).ensureIndex(new Index().on("completionTime", Order.ASCENDING));

    RabbitTemplate inboundTemplate = (RabbitTemplate) context.getBean("amqpTemplateInbound");
    Map<String, Object> messageMap = new HashMap<String, Object>();
    messageMap.put("count", "4");

    LOGGER.debug("Submitting first message which should pass DuplicateMessageFilter ok.");
    submitMessage(inboundTemplate, messageMap);

    Thread.sleep(5 * 1000);
    LOGGER.debug("Submitting a duplicate message which should get caught by the DuplicateMessageFilter.");
    submitMessage(inboundTemplate, messageMap);

    Thread.sleep(5 * 1000);
    messageMap.put("count", "0");
    LOGGER.debug("Submitting a message which will not go all the way through the message flow.");
    submitMessage(inboundTemplate, messageMap);

    Thread.sleep(5 * 1000);
    messageMap.put("count", "1");
    messageMap.put("fail", "true");
    LOGGER.debug("Submitting a message which should signal that an Exception should be thrown.");
    submitMessage(inboundTemplate, messageMap);

    Thread.sleep(6 * 60 * 1000);

    System.exit(0);

}

From source file:demo.jaxrs.swagger.server.Server.java

public static void main(String args[]) throws Exception {
    new Server();
    System.out.println("Server ready...");

    Thread.sleep(5 * 6000 * 1000);
    System.out.println("Server exiting");
    System.exit(0);//from   w ww . j  a  va  2 s .  c o  m
}

From source file:DataLoader.java

public static void main(String[] args)
        throws IOException, ValidationException, LicenseException, JobExecutionAlreadyRunningException,
        JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException {

    System.out.println(/*from w  ww .  j  av  a  2 s. c  om*/
            "System is initialising. Please wait for a few seconds then type your queries below once you see the prompt (->)");

    C24.init().withLicence("/biz/c24/api/license-ads.dat");

    // Create our application context - assumes the Spring configuration is in the classpath in a file called spring-config.xml
    ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

    // ========================================================================
    // DEMO
    // A simple command-line interface to allow us to query the GemFire regions
    // ========================================================================

    GemfireTemplate template = context.getBean(GemfireTemplate.class);

    BufferedReader br = new BufferedReader(new java.io.InputStreamReader(System.in));

    boolean writePrompt = true;

    try {
        while (true) {
            if (writePrompt) {
                System.out.print("-> ");
                System.out.flush();
                writePrompt = false;
            }
            if (br.ready()) {
                try {

                    String request = br.readLine();
                    System.out.println("Running: " + request);
                    SelectResults<Object> results = template.find(request);
                    System.out.println();
                    System.out.println("Result:");
                    for (Object result : results.asList()) {
                        System.out.println(result.toString());
                    }
                } catch (Exception ex) {
                    System.out.println("Error executing last command " + ex.getMessage());
                    //ex.printStackTrace();
                }

                writePrompt = true;

            } else {
                // Wait for a second and try again
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException ioEx) {
                    break;
                }
            }
        }
    } catch (IOException ioe) {
        // Write any exceptions to stderr
        System.err.print(ioe);
    }

}

From source file:com.msopentech.ThaliClient.ProxyDesktop.java

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

    final ProxyDesktop instance = new ProxyDesktop();
    try {// w  ww.  j a va 2s  .  c o  m
        instance.initialize();
    } catch (RuntimeException e) {
        System.out.println(e);
    }

    // Attempt to launch the default browser to our page
    if (Desktop.isDesktopSupported()) {
        Desktop.getDesktop().browse(new URI("http://localhost:" + localWebserverPort));
    }

    // Register to shutdown the server properly from a sigterm
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            instance.shutdown();
        }
    });

    // Let user press enter to kill the console session
    Console console = System.console();
    if (console != null) {
        console.format("\nPress ENTER to exit.\n");
        console.readLine();
        instance.shutdown();
    } else {
        // Don't exit on your own when running without a console (debugging in an IDE).
        while (true) {
            Thread.sleep(500);
        }
    }
}

From source file:com.alexoree.jenkins.Main.java

public static void main(String[] args) throws Exception {
    // create Options object
    Options options = new Options();

    options.addOption("t", false, "throttle the downloads, waits 5 seconds in between each d/l");

    // automatically generate the help statement
    HelpFormatter formatter = new HelpFormatter();
    formatter.printHelp("jenkins-sync", options);

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);
    boolean throttle = cmd.hasOption("t");

    String plugins = "https://updates.jenkins-ci.org/latest/";
    List<String> ps = new ArrayList<String>();
    Document doc = Jsoup.connect(plugins).get();
    for (Element file : doc.select("td a")) {
        //System.out.println(file.attr("href"));
        if (file.attr("href").endsWith(".hpi") || file.attr("href").endsWith(".war")) {
            ps.add(file.attr("href"));
        }/*from  w w  w. java2s .c o  m*/
    }

    File root = new File(".");
    //https://updates.jenkins-ci.org/latest/AdaptivePlugin.hpi
    new File("./latest").mkdirs();

    //output zip file
    String zipFile = "jenkinsSync.zip";
    // create byte buffer
    byte[] buffer = new byte[1024];
    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);

    //download the plugins
    for (int i = 0; i < ps.size(); i++) {
        System.out.println("[" + i + "/" + ps.size() + "] downloading " + plugins + ps.get(i));
        String outputFile = download(root.getAbsolutePath() + "/latest/" + ps.get(i), plugins + ps.get(i));

        FileInputStream fis = new FileInputStream(outputFile);
        // begin writing a new ZIP entry, positions the stream to the start of the entry data
        zos.putNextEntry(new ZipEntry(outputFile.replace(root.getAbsolutePath(), "")
                .replace("updates.jenkins-ci.org/", "").replace("https:/", "")));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
        if (throttle)
            Thread.sleep(WAIT);
        new File(root.getAbsolutePath() + "/latest/" + ps.get(i)).deleteOnExit();
    }

    //download the json metadata
    plugins = "https://updates.jenkins-ci.org/";
    ps = new ArrayList<String>();
    doc = Jsoup.connect(plugins).get();
    for (Element file : doc.select("td a")) {
        //System.out.println(file.attr("href"));
        if (file.attr("href").endsWith(".json")) {
            ps.add(file.attr("href"));
        }
    }
    for (int i = 0; i < ps.size(); i++) {
        download(root.getAbsolutePath() + "/" + ps.get(i), plugins + ps.get(i));

        FileInputStream fis = new FileInputStream(root.getAbsolutePath() + "/" + ps.get(i));
        // begin writing a new ZIP entry, positions the stream to the start of the entry data
        zos.putNextEntry(new ZipEntry(plugins + ps.get(i)));
        int length;
        while ((length = fis.read(buffer)) > 0) {
            zos.write(buffer, 0, length);
        }
        zos.closeEntry();
        fis.close();
        new File(root.getAbsolutePath() + "/" + ps.get(i)).deleteOnExit();
        if (throttle)
            Thread.sleep(WAIT);
    }

    // close the ZipOutputStream
    zos.close();
}

From source file:barrysw19.calculon.fics.FICSInterface.java

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

    if (System.getProperty("calculon.password") == null) {
        log.log(Level.SEVERE, "password must be specified.");
        System.exit(-1);//w  w  w.j av a 2 s  .co m
    }

    while (!shutdown) {
        try {
            new FICSInterface().connect();
        } catch (Exception x) {
            log.log(Level.SEVERE, "Error", x);
            try {
                Thread.sleep(60000);
            } catch (InterruptedException ignored) {
            }
        }
    }
}

From source file:com.camel.crawler.WebCrawler.java

public static void main(String[] args) {
    WebCrawler crawler = new WebCrawler();

    boolean finished = true;

    while (finished) {
        try {/*  w  w  w.  j  a v a 2s.c  o  m*/
            pageInit++;
            System.out.println("url num:=" + pageInit);
            try {
                crawler.fetchWeb(URL_PRE + String.valueOf(pageInit) + "/");
            } catch (IOException e) {
                pageInit--;
                e.printStackTrace();
                //?1?
                try {
                    System.out.println("exception sleep 1 min");
                    Thread.sleep(60000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
            //????crawler
            if (pageInit == pageEnd) {
                finished = false;
            }
            try {
                Thread.sleep(700);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            System.out.println("unknow exception");
            e.printStackTrace();
        }
    }
}

From source file:RegUnsol.java

public static void main(String[] args) {

    // Set up environment for creating initial context
    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDItutorial");

    try {/*from www  .  jav a2s  .c  o  m*/
        // Get event context for registering listener
        EventContext ctx = (EventContext) (new InitialContext(env).lookup("ou=People"));

        // Create listener
        NamingListener listener = new UnsolListener();

        // Register listener with context (all targets equivalent)
        ctx.addNamingListener("", EventContext.ONELEVEL_SCOPE, listener);

        // Wait 1 minutes for listener to receive events
        try {
            Thread.sleep(60000);
        } catch (InterruptedException e) {
            System.out.println("sleep interrupted");
        }

        // Not strictly necessary if we're going to close context anyhow
        ctx.removeNamingListener(listener);

        // Close context when we're done
        ctx.close();

    } catch (NamingException e) {
        e.printStackTrace();
    }
}

From source file:Example6.java

public static void main(String[] args) throws IOException, InterruptedException {
    //check if the executable exists
    File file = new File("./examples/dtlz2_socket.exe");

    if (!file.exists()) {
        if (!SystemUtils.IS_OS_UNIX) {
            System.err.println(//  w w w .java  2s  .  c  om
                    "This example only works on POSIX-compliant systems; see the Makefile for details");
            return;
        }

        System.err.println("Please compile the executable by running make in the ./examples/ folder");
        return;
    }

    //run the executable and wait one second for the process to startup
    new ProcessBuilder(file.toString()).start();
    Thread.sleep(1000);

    //configure and run the DTLZ2 function
    NondominatedPopulation result = new Executor().withProblemClass(MyDTLZ2.class).withAlgorithm("NSGAII")
            .withMaxEvaluations(10000).run();

    //display the results
    System.out.format("Objective1  Objective2%n");

    for (Solution solution : result) {
        System.out.format("%.4f      %.4f%n", solution.getObjective(0), solution.getObjective(1));
    }
}

From source file:com.claytablet.app.MockCron.java

/**
 * @param args/*from   w  w w.  j  ava2s .  c o m*/
 * @throws Exception
 */
public static void main(String args[]) throws Exception {

    log.debug("Initialize dependencies.");

    // setup the preferred Guice injector for DI
    Injector injector = Guice.createInjector(new MockProviderModule());

    // load the listener
    EventListener listener = injector.getInstance(EventListener.class);

    // load the poller
    ProviderStatePoller poller = injector.getInstance(ProviderStatePoller.class);

    log.debug("Start the endless loop.");
    while (true) {

        log.debug("Check for messages.");
        listener.checkMessages(MAX_MESSAGES);

        log.debug("Check for state changes.");
        poller.poll();

        log.debug("Retrieve the asset task mappings.");
        AssetTaskMap assetTaskMap = injector.getInstance(AssetTaskMap.class);
        if (assetTaskMap.size() > 0) {
            log.debug("Save the asset task mappings.");
            assetTaskMap.save();
        }

        log.debug("sleeping for " + SLEEP_INTERVAL + " seconds.");
        Thread.sleep(SLEEP_INTERVAL * 1000);

    }

}