我是否可以跳过当前执行延迟或立即重新启动预定执行服务?

时间:2017-01-01 21:01:30

标签: java android scheduledexecutorservice

我有一个计划执行服务,每隔X秒执行一次方法。是否可以使用一种方法可以强制计划执行服务跳过执行延迟中的剩余时间并立即调用该方法。或者我可以简单地停止并立即重新启动它吗?

这是我的代码:

Runnable runnable = new Runnable() {
    public void run() {

        callTheFunction();

    }
};

ScheduledExecutorService executor;
executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(Runnable, 0, 5, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat

public void restartTheExecutor() {
    // code to restart it or skip the remaining time.
}

这是我更新和工作的代码,它在参数中包含一个布尔值,第一次运行时必须设置为false。

public void restartExecutor(View v, boolean stopRequiered) {

    if (stopRequiered) {
        scheduled.cancel(true);
    }

    Runnable runnable = new Runnable() {
        public void run() {
            nextExpression();
        }
    };

    ScheduledExecutorService executor;
    executor = Executors.newScheduledThreadPool(1);
    scheduled = executor.scheduleAtFixedRate(runnable, 0, 3, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat

}

1 个答案:

答案 0 :(得分:2)

无法强制执行预定功能以立即使用ScheduledExecutorService运行。

然而,对于第二个问题,答案是肯定的。您可以随时删除任何计划的功能并根据需要运行它。您需要单独引用该功能:

Runnable runnable = new Runnable() {
    public void run() {
        callTheFunction();
    }
};

ScheduledExecutorService executor;
executor = Executors.newScheduledThreadPool(1);
Future<?> scheduled = executor.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat

// cancel and run immediately:
scheduled.cancel(true);
runnable.run();

请注意,cancel()不仅会取消下一个(或当前)运行,还会取消将来的所有运行。因此,您必须重新安排时间:

// reassigned scheduled to next runs:
scheduled = executor.scheduleAtFixedRate(runnable, 5, 5, TimeUnit.SECONDS); // 5 sec delay | 5 sec repeat

或者通过异步运行0s延迟和5s再次重复执行这两个步骤:

scheduled.cancel(true);
scheduled = executor.scheduleAtFixedRate(runnable, 0, 5, TimeUnit.SECONDS); // 0 sec delay | 5 sec repeat