如何在Spring中使用带有@Scheduled批注的Cron表达式?

问题描述 投票:0回答:1

我是春季的调度员新手。我在@scheduled,ScheduledExecutorService和TimerTask上阅读了很多文章。

据我所知,@ scheduled和ScheduledExecutorService具有大多数相同的功能,但是如果您的代码是春季版本,则最好在代码中使用@Scheduled批注。

因此,我的问题是,我想在程序启动15分钟后运行某些任务,这意味着初始延迟为15分钟,并且该任务应每隔5分钟运行一次,这意味着fixedRate为5分钟。那么如何使用cron表达式来实现呢?

阅读以下链接:

  1. https://dzone.com/articles/schedulers-in-java-and-spring
  2. https://crontab.guru/#15_ _ _ _
  3. https://www.baeldung.com/spring-scheduled-tasks

我可以使用以下代码实现相同的功能,但我想使用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);
    }
}
java spring spring-boot scheduler
1个回答
0
投票

您不能混合使用intial-delay和cron。当延迟和速率不足并且您需要更大的灵活性时,将使用cron。

但是您可以像这样每隔15分钟安排cron进行安排:

@Scheduled(cron = "* /15 * * * *)

© www.soinside.com 2019 - 2024. All rights reserved.