如何在Spring Java中动态调度任务

时间:2018-11-07 16:16:03

标签: java spring

我想动态安排任务,例如我有任务A,B,C。 我想在上午9点执行任务“ A”,在下午12.30执行任务“ B”,在晚上7点执行任务“ C”。 但是我不想每天重复同一时间的任务。 我想动态地设置任务时间表。 我已经用Google搜索了很多,我发现只有静态任务调度程序。 在春季java中,我只修复了  像这样的cron表达式@Scheduled(cron =“ 0 15 10 15 *?”)完全是静态的,对于cron表达式,您只需在一天的固定时间运行任务即可。 所以请帮助我。

2 个答案:

答案 0 :(得分:6)

我认为您正在寻找(来自official documentation):

  

Spring TaskScheduler抽象

     

除了TaskExecutor抽象之外,Spring 3.0还引入了一个   TaskScheduler具有多种安排任务运行的方法   在将来的某个时候。以下清单显示了   TaskScheduler界面定义:

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可以在指定的DateInstant安排任务:

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"));

答案 1 :(得分:0)

我喜欢在春季。

//9 AM every day
@Scheduled(cron="0 0 9 * * *")
public void checkDataScheduler() {
   DoSomething();
}

//every 15 min
@Scheduled(cron="0 */15 * * * *")
public void checkDataScheduler() {
   DoSomething();
}