BTakacs
BTakacs

Reputation: 2427

Pause and resume scheduled task

I need to pause and resume a scheduled task.

I see many code examples to cancel() a task, but I would need then to resume/restart it also. I see suggestions doing this:

public void init(){
    scheduledTaskExecutor.getScheduledThreadPoolExecutor().setRemoveOnCancelPolicy(true);
}
public void schedule(String id, Runnable task){
    ScheduledFuture<?> scheduledFuture = scheduledTaskExecutor.scheduleAtFixedRate(task);
    runningTaskRegistry.put(id, task);
}

public void suspend(String id){
    ScheduledFuture<?> scheduledFuture = runningTaskRegistry.get(serviceName);
    if(scheduledFuture != null){
        scheduledFuture.cancel(false);
        try{
            scheduledFuture.get();
        } catch (InterruptedException | ExecutionException | CancellationException e){
            // I do not want the currently running task finishing after this point
        }
    }
}

...and then I need to schedule again instead of restart.

Is that REALLY the best way to do this?

Upvotes: 3

Views: 2567

Answers (1)

beatngu13
beatngu13

Reputation: 9453

I'd prefer rescheduling over pausing and resuming. Not just because I don't know how to do this, but also because paused tasks probably won't release their threads. During this time, those executor threads block and do nothing even if there're other tasks waiting in the task queue.

To not lose intermediate results, you could put them in another queue which are picked up before new tasks are scheduled. You could also implement pausing and resuming based on that queue.

Upvotes: 1

Related Questions