是否可以每小时将带有 Spring @Scheduled 注释的作业安排到 运行,但每次都是随机时间?
Is it possible to schedule a job with Spring @Scheduled annotation to run every hour but each time at random hour?
我想 运行 我的 task/method 每小时..但每次都是随机的。
我已经尝试过 Spring @Scheduled to be started every day at a random minute between 4:00AM and 4:30AM 但此解决方案是设置随机初始值,但在使用同一分钟后。
我想实现这样的工作 运行ning 的情况。例如:
8:10
9:41
10:12
...
对,所以...这 不是 时间表。这是一个不确定的事件。
计划 事件是可重复的,并且可以在特定时间持续触发。有一种秩序和可预测性与此相辅相成。
通过在给定的时间触发作业而不是在给定的分钟,你失去了可预测性,这正是 @Scheduled
注释将强制执行的(不是必须通过实现,但作为副作用;注释可能只包含编译时常量,不能在运行时动态更改)。
至于解决方案,Thread.sleep
很脆弱,会导致您的 整个 应用程序休眠一段时间 不是你想做的。相反,you could wrap your critical code in a non-blocking thread 并安排它。
警告:以下代码未经测试
@Scheduled(cron = "0 0 * * * ?")
public void executeStrangely() {
// Based on the schedule above,
// all schedule finalization should happen at minute 0.
// If the pool tries to execute at minute 0, there *might* be
// a race condition with the actual thread running this block.
// We do *not* include minute 0 for this reason.
Random random = new Random();
final int actualMinuteOfExecution = 1 + random.nextInt(59);
final ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(() -> {
// Critical code here
}, actualMinuteOfExecution, TimeUnit.MINUTES);
}
我将以线程安全方式管理资源的工作留作 reader 的练习。
我想 运行 我的 task/method 每小时..但每次都是随机的。 我已经尝试过 Spring @Scheduled to be started every day at a random minute between 4:00AM and 4:30AM 但此解决方案是设置随机初始值,但在使用同一分钟后。
我想实现这样的工作 运行ning 的情况。例如:
8:10 9:41 10:12 ...
对,所以...这 不是 时间表。这是一个不确定的事件。
计划 事件是可重复的,并且可以在特定时间持续触发。有一种秩序和可预测性与此相辅相成。
通过在给定的时间触发作业而不是在给定的分钟,你失去了可预测性,这正是 @Scheduled
注释将强制执行的(不是必须通过实现,但作为副作用;注释可能只包含编译时常量,不能在运行时动态更改)。
至于解决方案,Thread.sleep
很脆弱,会导致您的 整个 应用程序休眠一段时间 不是你想做的。相反,you could wrap your critical code in a non-blocking thread 并安排它。
警告:以下代码未经测试
@Scheduled(cron = "0 0 * * * ?")
public void executeStrangely() {
// Based on the schedule above,
// all schedule finalization should happen at minute 0.
// If the pool tries to execute at minute 0, there *might* be
// a race condition with the actual thread running this block.
// We do *not* include minute 0 for this reason.
Random random = new Random();
final int actualMinuteOfExecution = 1 + random.nextInt(59);
final ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(() -> {
// Critical code here
}, actualMinuteOfExecution, TimeUnit.MINUTES);
}
我将以线程安全方式管理资源的工作留作 reader 的练习。