I'm using Spring's TaskScheduler to schedule a periodic task.
ScheduledFuture scheduleAtFixedRate(Runnable task, long period);
I understand that I can call cancel() on the ScheduledFuture to stop the recurring task from being executed. But I'd like to cancel the recurring scheduled task depending on the result of the execution of the task, and am not sure how to best do that.
Does the ScheduledFuture give me access to the result of EACH executed task? Or do I need some sort of task listener that can keep a reference to this ScheduledFuture, and cancel it that way? Or something else?
Ok it looks like it is possible, but there is probably a better approach.
Since a recurring job only takes a Runnable (with a void return type) there is no way to return the result of the task. So the only way to stop the recurring task is to make the task perform a side-effect, e.g. adding a stop message to a queue. Then a separate thread would need to monitor this queue, and it could cancel the job once it sees the message.
Very messy and complicated.
A better alternative is to create a normal (one time) scheduled task. The task itself can then decide whether or not it needs to schedule another task, and can do the scheduling of the next task itself.