ScheduledExecutorService with variable delay

前端 未结 5 2057
别那么骄傲
别那么骄傲 2020-12-09 03:44

Suppose I have a task that is pulling elements from a java.util.concurrent.BlockingQueue and processing them.

public void scheduleTask(int delay, TimeUnit ti         


        
5条回答
  •  执笔经年
    2020-12-09 04:17

    Use schedule(Callable, long, TimeUnit) rather than scheduleAtFixedRate or scheduleWithFixedDelay. Then ensure that your Callable reschedules itself or a new Callable instance at some point in the future. For example:

    // Create Callable instance to schedule.
    Callable c = new Callable() {
      public Void call() {
       try { 
         // Do work.
       } finally {
         // Reschedule in new Callable, typically with a delay based on the result
         // of this Callable.  In this example the Callable is stateless so we
         // simply reschedule passing a reference to this.
         service.schedule(this, 5000L, TimeUnit.MILLISECONDS);
       }  
       return null;
      }
    }
    
    service.schedule(c);
    

    This approach avoids the need to shut down and recreate the ScheduledExecutorService.

提交回复
热议问题