且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用ScheduledExecutorService更改重复任务的速率或周期?

更新时间:2023-01-12 18:08:04

我改进了答案(主要是因为我也必须使用 ScheduledExecutorService )。请使用此代码而不是我之前发布的代码,因为之前的代码实际上是在性能上,没有充分的理由。

I improved the answer a bit (mainly because I too had to use ScheduledExecutorService). Please use this code instead of the previous one I posted, because the previous one was really on performance, for no good reason.

private ScheduledExecutorService scheduledExecutorService;
private ScheduledFuture<?> futureTask;
private Runnable myTask;

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);

    // Your executor, you should instanciate it once for all
    scheduledExecutorService = Executors.newScheduledThreadPool(5);

    // Since your task won't change during runtime, you can instanciate it too once for all
    myTask = new Runnable()
    {
        @Override
        public void run()
        {
            // Your code to run periodically
        }
    };
}

/**
 * This method will reschedule "myTask" with the new param time
 */
public void changeReadInterval(long time)
{
    if(time > 0)
    {       
        if (futureTask != null)
        {
            futureTask.cancel(true);
        }

        futureTask = scheduledExecutorService.scheduleAtFixedRate(myTask, 0, time, TimeUnit.SECONDS);
    }
}

现在,要在运行时重新安排任务,请使用方法 changeReadInterval(时间);

Now, to reschedule your task during runtime, use the method changeReadInterval(time);

如果已经设置并将重新安排,它将取消之前的计时器一个新的。

It will cancel the previous "timer" if it has been set and will reschedule a new one.