如何在Spring Boot中安排任务并增加延迟?

时间:2018-10-10 15:43:45

标签: java spring-boot scheduler spring-scheduled

我需要安排一个任务,该任务将在10分钟后首先执行,然后是100,然后是1000,依此类推(基本上是10 ^ n)。 我发现@Scheduled仅接受常数作为参数。 如何实现延迟增量?

1 个答案:

答案 0 :(得分:2)

您可以将SchedulingConfigurer与自定义Trigger一起使用:

@Configuration
@EnableScheduling
public class Schedule implements SchedulingConfigurer {

@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
    taskRegistrar.setScheduler(taskScheduler());
    taskRegistrar.addTriggerTask(
            myTask(), new ExponentialTrigger()
    );
}

static class ExponentialTrigger implements Trigger {

    long n = 0;

    @Override
    public Date nextExecutionTime(TriggerContext triggerContext) {
        // delay from last scheduled time or completion time? pick yours 
        Date lastDate = triggerContext.lastScheduledExecutionTime(); 
        long last;
        if (lastDate == null) {
            last = System.currentTimeMillis();
        } else {
            last = lastDate.getTime();
        }

        return new Date(last + ((int) Math.pow(10, n++)) * 60_000); // * 60_000 millis to minutes
    }
}


@Bean(destroyMethod = "shutdown")
public ExecutorService taskScheduler() {
    return Executors.newScheduledThreadPool(42); // if you have single task, which is faster than delay then this can be 1
}

@Bean
public Runnable myTask() {
    return new Runnable() {
        @Override
        public void run() {
            System.out.println(System.currentTimeMillis());
        }
    };
}

}