Spring boot CRON 表达式不起作用

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

我使用 spring bootd,我想每周六上午 10 点运行 CRON。

我决定每 10 分钟运行一次 con,看看该函数是否被调用。

@Scheduled(cron = "0 */10 * * * *")
public void validation () {
    System.out.println("heolooooooooooooooooooooooooooooooooooooooooo");
}

当它

fixedRate
时,它正在工作。

@Scheduled(fixedRate = 1)
    public void consoleUserSqsListner() {
       System.out.println("heolooooooooooooooooooooooooooooooooooooooooo2");
    }

我的主要内容有:

@SpringBootApplication 
@EnableAsync 
@EnableScheduling 
public class MAppUserApplication {

请问这个问题是什么原因造成的?

spring-boot cron
1个回答
0
投票

fixedRate
从应用程序启动时开始运行,
@Scheduled(cron = "0 */10 * * * *")
表示“每10分钟运行一次”。它与时钟对齐,而不是与应用程序启动时间对齐。因此,无论您的应用程序何时启动,它都会在 00:00、00:10、00:20 等运行。

为了展示它是如何工作的,在下面编写了这个类

@Component
public class ScheduledJobForSomething {
    private static final Logger log = LoggerFactory.getLogger(ScheduledJobForSomething.class);

    @Scheduled(cron = "0 * * * * *")
    public void runeveryminute() {
        log.info("1 minute");
    }

    @Scheduled(cron = "0 0/10 * * * *", zone = "GMT")
    public void runEvery10Minutes() {
        log.info("1-------------------10 minutes:{}", Instant.now());
    }

    @Scheduled(cron = "0 */10 * * * *", zone = "GMT")
    public void runEvery10Minutes2() {
        log.info("2-------------------10 minutes:{}", Instant.now());
    }

    @Scheduled(cron = "*/60 * * * * *")
    public void runevery60seconds() {
        log.info("60 secs");
    }

    @Scheduled(fixedRate = 60_000)
    public void consoleUserSqsListner() {
        log.info("fixed rate 60 seconds");
    }
}

日志如下所示

2024-07-06T12:40:00.014+01:00  INFO 11952 --- [scheduled-demo] [   scheduling-1] i.g.o.s.ScheduledJobForSomething         : 1-------------------10 minutes:2024-07-06T11:40:00.014431600Z
2024-07-06T12:40:00.023+01:00  INFO 11952 --- [scheduled-demo] [   scheduling-1] i.g.o.s.ScheduledJobForSomething         : 2-------------------10 minutes:2024-07-06T11:40:00.023434400Z
2024-07-06T12:50:00.013+01:00  INFO 11952 --- [scheduled-demo] [   scheduling-1] i.g.o.s.ScheduledJobForSomething         : 1-------------------10 minutes:2024-07-06T11:50:00.013555600Z
2024-07-06T12:50:00.014+01:00  INFO 11952 --- [scheduled-demo] [   scheduling-1] i.g.o.s.ScheduledJobForSomething         : 2-------------------10 minutes:2024-07-06T11:50:00.014555200Z

参考:

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