tags:

views:

630

answers:

3

I want to write a loop in Java that firs starts up and goes like this:

while (!x){
    //wait one minute or two

    //execute code
}

I want to do this so that it does not use up system resources. What is actually going on in the code is that it goes to a website and checks to see if something is done, if it is not done, it should wait another minute until it checks again, and when its done it just moves on. Is their anyway to do this in java? I googled it but didnt find anything. Thanks

+3  A: 

Use Thread.sleep(long millis).

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. The thread does not lose ownership of any monitors.

One minute would be (60*1000) = 60000 milliseconds.


For example, this loop will print the current time once every 5 seconds:

    try {
        while (true) {
            System.out.println(new Date());
            Thread.sleep(5 * 1000);
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

If your sleep period becomes too large for int, explicitly compute in long (e.g. 1000L).

polygenelubricants
Thanks, I will try it out.
Robert
I tried it and it didnt work my code is as follows--if (link.equalsIgnoreCase("exit") int myCounter = 0;try {while (!fetched) {System.out.println("Checking (" + myCounter + ")");if (session.areLinkDoneFetching()) {session.getFetchData();session.clearList();fetched = true;}myCounter++;Thread.sleep(5 * 1000);}} catch (InterruptedException e) {e.printStackTrace();}}
Robert
What do you mean it "didn't work"? It doesn't compile? It doesn't sleep for 5 seconds at a time?
polygenelubricants
it runs once, and then doesnt do anything. but the program is still running.
Robert
its something wrong with my code, sorry, it works well on its own. thank you though, this was exactly what i was looking for
Robert
A: 
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.sechedule(yourRunnable, 1L, TimeUnit.MINUTES);

...

//When done
executor.shutdown();
Chuk Lee
Don't forget to [shutdown()](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#shutdown%28%29) it after use, else the thread will hang. Oh, the OP didn't ask for scheduling at fixed rate. Just use [schedule()](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ScheduledExecutorService.html#schedule%28java.lang.Runnable,%20long,%20java.util.concurrent.TimeUnit%29).
BalusC
+5  A: 

You can use Timer

Timer timer = new Timer();

timer.schedule( new TimerTask() {
    public void run() {
       // do your work 
    }
 }, 0, 60*1000);

When the times comes

  timer.cancel();

To shut it down.

OscarRyz
If the `TimerTask` takes, say, 55 seconds to run, will this wait only 5 seconds before each run, or will it actually wait a minute like OP asked?
polygenelubricants
@poly: It will wait a minute like OP asked. The [Timer#scheduleAtFixedRate()](http://java.sun.com/javase/6/docs/api/java/util/Timer.html#scheduleAtFixedRate%28java.util.TimerTask,%20long,%20long%29) does what you say.
BalusC
@BalusC: Ah, interesting! `schedule` runs with fixed delay between executions, and `scheduleAtFixedRate` runs at fixed interval. Nice!
polygenelubricants
I tried this one and put my code inside the run method but got an error about local variables being accessed from an inner class.
Robert