ScheduledExecutorService
El Answer by Lee está cerca, pero sólo se ejecuta una vez. La pregunta parece estar pidiendo ejecutarse indefinidamente hasta que un estado externo cambie (hasta que cambie la respuesta de un sitio web/servicio).
La interfaz ScheduledExecutorService
es parte del paquete java.util.concurrent
integrado en Java 5 y posterior como un reemplazo más moderno para la antigua clase Timer
.
Aquí hay un ejemplo completo. Llame al scheduleAtFixedRate
o 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();
}
esperan que la producción de esta manera:
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
Gracias, voy a probarlo. –
Lo probé y no funcionó mi código es el siguiente-- if (link.equalsIgnoreCase ("exit") && count> 0) { boolean fetched = false; int myCounter = 0; try { while (! Fetched) { System.out.println ("Comprobación (" + myCounter + ")"); if (session.areLinkDoneFetching()) { sesión.getFetchData(); session.clearList(); fetched = true; } myCounter ++; Thread.sleep (5 * 1000); } } catch (InterruptedException e) { e.printStackTrace(); } } –
¿Qué quiere decir que "no funcionó"? No compila? No duerme durante 5 segundos a la vez? – polygenelubricants