我是春季的调度员新手。我在@scheduled,ScheduledExecutorService和TimerTask上阅读了很多文章。
据我所知,@ scheduled和ScheduledExecutorService具有大多数相同的功能,但是如果您的代码是春季版本,则最好在代码中使用@Scheduled批注。
因此,我的问题是,我想在程序启动15分钟后运行某些任务,这意味着初始延迟为15分钟,并且该任务应每隔5分钟运行一次,这意味着fixedRate为5分钟。那么如何使用cron表达式来实现呢?
阅读以下链接:
我可以使用以下代码实现相同的功能,但我想使用cron表达式编写此代码。
代码:
@Configuration
@EnableScheduling
public class ScheduledConfiguration {
@Scheduled(fixedDelay = 5000, initialDelay = 1000)
public void scheduleFixedRateWithInitialDelayTask() {
long now = System.currentTimeMillis() / 1000;
System.out.println("Fixed rate task with one second initial delay - " + now);
}
}
您不能混合使用intial-delay和cron。当延迟和速率不足并且您需要更大的灵活性时,将使用cron。
但是您可以像这样每隔15分钟安排cron进行安排:
@Scheduled(cron = "* /15 * * * *)