bus*_*man 8 java scheduling timer timer-jobs
关于使用ScheduledThreadPoolExecutor执行某些重复任务,我正在跟进一个有趣的问题.
调度此对象将返回ScheduledFuture对象,可以使用该对象取消下一次任务运行.
这里要注意的一件事是任务本身与时间表完全脱钩 -
ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1);
ScheduledFuture nextSchedule =
executor.schedule(task, 60000, TimeUnit.MILLISECONDS);
Run Code Online (Sandbox Code Playgroud)
哪里-
SomeTask task = new SomeTask();
Run Code Online (Sandbox Code Playgroud)
所以任务本身并不了解时间表.如果有办法让任务取消并为自己创建一个新的时间表,请启发.
谢谢
ScheduledExecutorService如果需要,没有理由为什么任务无法引用并安排自己再次运行:
// (Need to make variable final *if* it is a local (method) variable.)
final ScheduledExecutorService execService = Executors.newSingleThreadScheduledExecutor();
// Create re-usable Callable. In cases where the Callable has state
// we may need to create a new instance each time depending on requirements.
Callable<Void> task = new Callable() {
public Void call() {
try {
doSomeProcessing();
} finally {
// Schedule same task to run again (even if processing fails).
execService.schedule(this, 1, TimeUnit.SECONDS);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6308 次 |
| 最近记录: |