I have a task I want to run where the delay will keep changing (ie - no fixed interval).
I want a thread and loops infinitely that finds the delay value, inputs this into the executor and then once that task is done find the new delay value etc..
My current 'basic' implementation:
long targetTime = findNextTime()/1000;
long currentTime = System.curentTimeMillis()/1000;
delay = targetTime - currentTime;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(3);
Runnable task = new Runnable() {
public void run() {
System.out.println("Test Task");
ScheduledFuture<?> future = scheduler.schedule(this, delay, TimeUnit.SECONDS);
}
}
How can I get it to find the new delay and keep repeating this task?
Should I poll for future
to be done and then do a recursive loop? I try this and I get an error.
There are some answer to resolve this. Reinitialize fix delay in ScheduledExecutorService and How to change Spring's @Scheduled fixedDelay at runtime
here i support another method to realize this-repeated submit task to ExecutorService
class Task implements Runnable {
private static Random random = new Random();
private ExecutorService executor;
public Task(ExecutorService executor) {
this.executor = executor;
}
@Override
public void run() {
try {
System.out.println(System.currentTimeMillis() + " Hello World");
TimeUnit.MILLISECONDS.sleep(random.nextInt() % 100);
executor.execute(this);
} catch (Exception e) {
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.