【问题标题】:ScheduledExecutorService - Conditionally terminate taskScheduledExecutorService - 有条件地终止任务
【发布时间】:2022-01-23 08:23:06
【问题描述】:

我正在安排线程池上的任务。我的要求是每个任务最多将相同的逻辑迭代 4 次,但在每次迭代之前,如果满足某些条件,我想终止该任务。

调度任务->

ScheduledExecutorService scheduledExecutorService;

// Submitting the task to the thread pool
scheduledExecutorService.scheduleAtFixedRate(new Task(payload),
            AppConstants.INITIAL_DELAY_IN_MINUTES,
            AppConstants.INTERVAL_BETWEEN_DELIVERY_IN_MINUTES,
            TimeUnit.MINUTES);

Task类的run方法(实现Runnable)->

@Override
public void run() {
        if (shouldTaskTerminate())
            terminateTask("Counter reached it's upper bound for " + payload.getEventId());

        // Handling the task if the above condition is not satisfied

    }

private void terminateTask(String taskTerminationReason) {
    log.info(" {}. So, cancelling the task of {} ", taskTerminationReason, Thread.currentThread().getId());
    throw new RuntimeException("Task lifecycle completed.");
}

正如上面代码sn-p中提到的,我抛出一个异常来终止任务。我通过参考JavaDoc here了解了这种终止任务的方式。

这是终止任务的正确方法吗?我还知道,当我将任务提交到线程池时,另一种终止任务的方法是取消未来对象。但是,就我而言,我想在 Task 类(即 Runnable 实现者)中终止它,因为 Task 类中定义的变量/数据库查询决定了未来的运行。

【问题讨论】:

  • 已经有一些类似的问题了,大家可以看看:link1,link2

标签: java multithreading


【解决方案1】:

这是一种终止定期调度的方法。 我认为它很丑,但它是最简单的东西,我认为实用主义是一种美德。

正确吗?如果你想停止调度,并且你可以在调度方法返回的ScheduledFuture 中反映该异常,那么我会说你很高兴。只需确保记录您抛出异常的“原因”,包括指向 javadoc 的链接。

这不是你能做到这一点的唯一方法:我在回复 question 时描述了 2 个替代方案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-15
    • 1970-01-01
    • 2020-05-13
    • 2018-07-06
    • 1970-01-01
    相关资源
    最近更新 更多