java - java - 如何在spring java中动态调度任务

标签 java spring

我想动态安排任务,例如我有任务 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 a TaskScheduler with a variety of methods for scheduling tasks to run at some point in the future. The following listing shows the TaskScheduler 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/

相关文章:

java - System.out.println 中字符串的相等性检查

java - 反编译 jar 文件以将其用作 intellij 中的项目

java - Java Map 中的 put() 函数如何工作?

java - minikube 中的损坏 jar

java - 如何找到给定月份的星期六和星期日?

java - 将 SWT 小部件添加到 swing JPanel

java - Spring + Quartz,触发器为空

java - Android 设备针对 Spring Security Rest API 的身份验证

java - 如何使2个不相关的实体(两个存储库)同时在一个项目中运行?是否可以?

java - 请求处理失败;嵌套异常是 org.springframework.transaction.CannotCreateTransactionException