Search code examples
javascheduled-tasksscheduling

Supressing redundant jobs in ScheduledThreadPoolExecutor


I am using the ScheduledThreadPoolExecutor to execute periodic tasks. It is essential that the execution be periodic, not with fixed delay.

I encountered the following problem: consider a period of 1 minute for a task. If the task takes 5 minutes to execute (e.g. because of a temporary network problem), the missed executions get queued up and dispatched immediately after the task finishes. Is there a way to get rid of the accumulated executions that were missed?

I tried using the remove method, but it removes the task completely, not only a specific execution.

Thanks


Solution

  • There might be a better way, but you could have your task reschedule itself. That way, one execution will always run 1 minute after the previous execution has finished:

    final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    Runnable yourTask = new Runnable() {
    
        @Override
        public void run() {
            //do your stuff
            scheduler.schedule(this, 1, TimeUnit.MINUTES);
        }
    };
    scheduler.schedule(yourTask, 1, TimeUnit.MINUTES);
    

    EDIT

    If you want your task to run exactly at hh:mm:00 (exact minute) you can replace the code by

    long millisToNextMinute = 60000 - System.currentTimeMillis() % 60000;
    scheduler.schedule(this, millisToNextMinute, TimeUnit.MILLISECONDS);