Reputation: 1640
I want to do some timing tasks using ScheduledExecutorService
, but time intervals are changeable. I try to reschedule a task before it finished:
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class Test {
public static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
public static int interval = 1;
public static void main(String[] args) throws IOException {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(System.currentTimeMillis() / 1000);
interval += 1;
scheduledExecutorService.schedule(this, interval, TimeUnit.SECONDS);
}
};
scheduledExecutorService.schedule(runnable, interval, TimeUnit.SECONDS);
}
}
But, I never found anyone do timing tasks using ScheduledExecutorService
like this, I wonder whether it's safe.
Upvotes: 2
Views: 499
Reputation: 44965
As long as you use the method schedule
that executes the task only once, there is nothing wrong with this approach, it will only re-schedule at each iteration the same task with a different delay. For the scheduler it will be seen as a new task scheduled at each iteration, nothing more.
Upvotes: 2