I have a specific task which has to be executed periodically, or just once based on a condition. I am using the following approach:
Runnable r = new Runnable() {
public void run()
{
//Execute task
}
};
final long freq = frequencyOfTask;
ScheduledExecutorService dataTimer = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> dataTimerHandle = dataTimer.scheduleAtFixedRate(r, 0L, freq, TimeUnit.MILLISECONDS);
if(!isDynamic)
{
dataTimerHandle.cancel(false); //cancel the event in main thread while asking the already submitted tasks to complete.
}
The task runs fine for the case where isDynamic
is false
, i.e., where the task is not cancelled. But, for the other case (when the execution is required just once) it doesn't execute at all.