I'd like to create a method that delays the execution on method invocation by 60s.
Problem: if the method is called within that 60s, I want it to be delayed again by 60s from last point of invocation. If then not called within 60s, the execution may continue.
I started as follows, but of course this is only a one-time delay:
public void sendDelayed(String info) {
//TODO create a task is delayed by +60s for each method invocation
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.schedule(Classname::someTask, 60, TimeUnit.SECONDS);
}
How could I further delay the execution on each invocation?
executorService.schedulereturns aScheduledFuturewhich provides acancelmethod to cancel its execution.canceltakes a single boolean parametermayInterruptIfRunningwhich, when set tofalse, will only cancel the execution if the task has not started yet. See also the docs.Using this you could do something like this:
You may have to take care of avoiding race conditions regarding concurrent access to the
futurefield though.