我想动态安排任务,例如我有任务 A、B、C。
我想在上午 9 点执行任务“A”,在下午 12.30 执行任务“B”,在晚上 7 点执行任务“C”。
但我不想每天在同一时间重复任务。
我想动态设置任务计划。
我用谷歌搜索了很多,我发现只有静态任务调度程序。
在spring java中,我只得到了固定和
像这样的 cron 表达式 @Scheduled(cron = "0 15 10 15 * ?") 完全是静态的,对于 cron 表达式,您可以在一天的固定时间运行任务。
所以请帮助我。
最佳答案
我想你正在寻找这个(来自 official documentation ):
The Spring TaskScheduler Abstraction
In addition to the
TaskExecutor
abstraction, Spring 3.0 introduced aTaskScheduler
with a variety of methods for scheduling tasks to run at some point in the future. The following listing shows theTaskScheduler
interface definition:public interface TaskScheduler { ScheduledFuture schedule(Runnable task, Trigger trigger); ScheduledFuture schedule(Runnable task, Instant startTime); ScheduledFuture schedule(Runnable task, Date startTime); ScheduledFuture scheduleAtFixedRate(Runnable task, Instant startTime, Duration period); ScheduledFuture scheduleAtFixedRate(Runnable task, Date startTime, long period); ScheduledFuture scheduleAtFixedRate(Runnable task, Duration period); ScheduledFuture scheduleAtFixedRate(Runnable task, long period); ScheduledFuture scheduleWithFixedDelay(Runnable task, Instant startTime, Duration delay); ScheduledFuture scheduleWithFixedDelay(Runnable task, Date startTime, long delay); ScheduledFuture scheduleWithFixedDelay(Runnable task, Duration delay); ScheduledFuture scheduleWithFixedDelay(Runnable task, long delay); }
TaskScheduler
可以在指定的 Date
安排任务或 Instant
:ScheduledFuture schedule(Runnable task, Instant startTime);
ScheduledFuture schedule(Runnable task, Date startTime);
所以你应该能够做到:
scheduler.schedule(task, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format("2018-11-07 17:46:00"));
关于java - java - 如何在spring java中动态调度任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53193490/