ScheduledExecutorService
The Answer by Lee is close, but only runs once. The Question seems to be asking to run indefinitely until an external state changes (until the response from a web site/service changes).
The ScheduledExecutorService
interface is part of the java.util.concurrent
package built into Java 5 and later as a more modern replacement for the old Timer
class.
Here is a complete example. Call either scheduleAtFixedRate
or scheduleWithFixedDelay
.
ScheduledExecutorService executor = Executors.newScheduledThreadPool ( 1 );
Runnable r = new Runnable () {
@Override
public void run () {
try { // Always wrap your Runnable with a try-catch as any uncaught Exception causes the ScheduledExecutorService to silently terminate.
System.out.println ( "Now: " + Instant.now () ); // Our task at hand in this example: Capturing the current moment in UTC.
if ( Boolean.FALSE ) { // Add your Boolean test here to see if the external task is fonud to be completed, as described in this Question.
executor.shutdown (); // 'shutdown' politely asks ScheduledExecutorService to terminate after previously submitted tasks are executed.
}
} catch ( Exception e ) {
System.out.println ( "Oops, uncaught Exception surfaced at Runnable in ScheduledExecutorService." );
}
}
};
try {
executor.scheduleAtFixedRate ( r , 0L , 5L , TimeUnit.SECONDS ); // ( runnable , initialDelay , period , TimeUnit )
Thread.sleep ( TimeUnit.MINUTES.toMillis ( 1L ) ); // Let things run a minute to witness the background thread working.
} catch ( InterruptedException ex ) {
Logger.getLogger ( App.class.getName () ).log ( Level.SEVERE , null , ex );
} finally {
System.out.println ( "ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed." );
executor.shutdown ();
}
Expect output like this:
Now: 2016-12-27T02:52:14.951Z
Now: 2016-12-27T02:52:19.955Z
Now: 2016-12-27T02:52:24.951Z
Now: 2016-12-27T02:52:29.951Z
Now: 2016-12-27T02:52:34.953Z
Now: 2016-12-27T02:52:39.952Z
Now: 2016-12-27T02:52:44.951Z
Now: 2016-12-27T02:52:49.953Z
Now: 2016-12-27T02:52:54.953Z
Now: 2016-12-27T02:52:59.951Z
Now: 2016-12-27T02:53:04.952Z
Now: 2016-12-27T02:53:09.951Z
ScheduledExecutorService expiring. Politely asking ScheduledExecutorService to terminate after previously submitted tasks are executed.
Now: 2016-12-27T02:53:14.951Z