在 ScheduledThreadPoolExecutor 中抑制冗余作业 [英] Supressing redundant jobs in ScheduledThreadPoolExecutor

查看:37
本文介绍了在 ScheduledThreadPoolExecutor 中抑制冗余作业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ScheduledThreadPoolExecutor 来执行周期性任务.执行必须是周期性的,不是固定延迟.

I am using the ScheduledThreadPoolExecutor to execute periodic tasks. It is essential that the execution be periodic, not with fixed delay.

我遇到了以下问题:考虑一个任务的时间为 1 分钟.如果任务需要 5 分钟来执行(例如,由于临时网络问题),错过 的执行会在任务完成后立即排队并分派.有没有办法摆脱错过的累积执行?

I encountered the following problem: consider a period of 1 minute for a task. If the task takes 5 minutes to execute (e.g. because of a temporary network problem), the missed executions get queued up and dispatched immediately after the task finishes. Is there a way to get rid of the accumulated executions that were missed?

我尝试使用 remove 方法,但它完全删除了任务,而不仅仅是特定的执行.

I tried using the remove method, but it removes the task completely, not only a specific execution.

谢谢

推荐答案

可能有更好的方法,但您可以自行重新安排任务.这样,一次执行将始终在前一次执行完成后运行 1 分钟:

There might be a better way, but you could have your task reschedule itself. That way, one execution will always run 1 minute after the previous execution has finished:

final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Runnable yourTask = new Runnable() {

    @Override
    public void run() {
        //do your stuff
        scheduler.schedule(this, 1, TimeUnit.MINUTES);
    }
};
scheduler.schedule(yourTask, 1, TimeUnit.MINUTES);

编辑

如果您希望您的任务恰好在 hh:mm:00(精确分钟)运行,您可以将代码替换为

If you want your task to run exactly at hh:mm:00 (exact minute) you can replace the code by

long millisToNextMinute = 60000 - System.currentTimeMillis() % 60000;
scheduler.schedule(this, millisToNextMinute, TimeUnit.MILLISECONDS);

这篇关于在 ScheduledThreadPoolExecutor 中抑制冗余作业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆