2012-03-15 77 views
0

从Android开发人员参考:取消()和定期的计划任务

public abstract boolean cancel (boolean mayInterruptIfRunning) 

If the task has already started, then the mayInterruptIfRunning parameter 
determines whether the thread executing this task should be interrupted in 
an attempt to stop the task. 

这显然对我来说,谈论仅出现一次的任务时。但不是,当我有周期性的任务时,我想让它完成当前的“任务”,但不能开始新的任务。

是不是可以直接使用那些直接使用的盒子?我认为如果将参数设置为true,它可以在完成之前停止当前任务,并且如果将其更改为false,并且当前有一个任务正在运行,则它不执行任何操作。这是正确的吗?

我将如何实现我想要的?我是否应该以某种方式轮询任务以查找它是否正在运行,并在发现它不是时候取消它?

回答

0

不确定你的环境的细节,但据我所知,你正在使用一些执行从java.util.concurrent定期任务安排。

基本参数cancel()决定是否强制终止运行线程。如果设置为false,则只需让程序员通过检查isCanceled()(来自FutureRunnable的某些内容)来决定何时中断正在运行的线程。

所以致电cancel(false)方法SheduledFuture返回Executor应该为你工作。这不会中断正在运行的任务并阻止它再次运行。在调用它之后,Future.get()将抛出一个异常,这将导致执行程序不在下一个预定时间运行它。

0

使用ScheduledThreadPoolExecutor.shutdown()

... ... 
// At some point in the future if you want reject next periodic task submit 
// after waiting for current periodic task finish. 
scheduledThreadPoolExecutor.shutdown(); // <-- this will reject next periodic task submit. 
scheduledThreadPoolExecutor.awaitTermination(10, TimeUnit.SECONDS); // <-- this will wait current periodic task finish. 
... ... 

awaitTermination()必须关机后调用(),这是不明确在Android API说明,但是,你可以找到从official Java API详细文档。