【问题标题】:Cancel() and periodic scheduled taskCancel() 和周期性计划任务
【发布时间】:2012-04-01 12:58:58
【问题描述】:

来自 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,并且当前有一个任务正在运行,它什么也不做。是这样吗?

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

【问题讨论】:

    标签: android scheduled-tasks


    【解决方案1】:

    不确定您的环境的详细信息,但据我了解,您正在使用来自java.util.concurrent 的一些执行程序,用于安排定期任务。

    cancel()的基本参数决定是否强制终止正在运行的线程。如果它被设置为 false ,那么它只会让程序员通过检查 isCanceled() 来决定何时中断正在运行的线程(说到从 FutureRunnable 派生的东西)。

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

    【讨论】:

      【解决方案2】:

      使用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() 必须在shutdown() 之后调用,这在Android API 中没有明确说明,但是您可以从official Java API 找到详细文档。

      【讨论】:

        猜你喜欢
        • 2015-02-19
        • 2023-04-01
        • 1970-01-01
        • 2019-05-25
        • 1970-01-01
        • 2019-02-16
        • 2022-12-07
        • 2018-11-28
        • 1970-01-01
        相关资源
        最近更新 更多