ScheduledExecutorService with variable delay

前端 未结 5 2098
别那么骄傲
别那么骄傲 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:05

    I had to do this recently using ScheduledFuture and didn't want to wrap Runnable or such. Here's how I did it:

    private ScheduledExecutorService scheduleExecutor;
    private ScheduledFuture scheduleManager;
    private Runnable timeTask;
    
    public void changeScheduleTime(int timeSeconds){
        //change to hourly update
        if (scheduleManager!= null)
        {
            scheduleManager.cancel(true);
        }
        scheduleManager = scheduleExecutor.scheduleAtFixedRate(timeTask, timeSeconds, timeSeconds, TimeUnit.SECONDS);
    }
    
    public void someInitMethod() {
    
        scheduleExecutor = Executors.newScheduledThreadPool(1);    
        timeTask = new Runnable() {
            public void run() {
                //task code here
                //then check if we need to update task time
                if(checkBoxHour.isChecked()){
                    changeScheduleTime(3600);
                }
            }
        };
    
        //instantiate with default time
        scheduleManager = scheduleExecutor.scheduleAtFixedRate(timeTask, 60, 60, TimeUnit.SECONDS);
    }
    

提交回复
热议问题