SpringBoot-Scheduled

2020-09-29  本文已影响0人  张明学

Spring Framework 自身提供了对定时任务的支持,本文介绍 Spring Boot 中 @Scheduled 定时器的使用。

开启对定时任务的支持

在项目启动类上添加 @EnableScheduling 注解。

@SpringBootApplication(scanBasePackages = "zmx.study")
@EnableScheduling
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

编写定时任务类和方法

@Component
@Slf4j
public class SampleJob {

    @Scheduled(cron = "0 0/3 * * * ? ")
    public void scheduledTask(){
        log.info("scheduledTask");
    }

}

配置说明

cron [秒] [分] [小时] [日] [月] [周] [年]
说明 必填 允许填写的值 允许的通配符
0-59 , - * /
0-59 , - * /
小时 0-23 , - * /
1-31 , - * ? / L W
1-12 / JAN-DEC , - * /
1-7 or SUN-SAT , - * ? / L #
1970-2099 , - * /
通配符说明:
fixedDelay

上一次执行完毕时间点之后多长时间再执行。如:

@Scheduled(fixedDelay = 5000) //上一次执行完毕时间点之后5秒再执行
fixedDelayString

fixedDelay 意思相同,只是使用字符串的形式。唯一不同的是支持占位符。如:

@Scheduled(fixedDelayString = "${time.fixedDelay}")
void testFixedDelayString() {
        System.out.println("Execute at " + System.currentTimeMillis());
}
fixedRate、fixedRateString

上一次开始执行时间点之后多长时间再执行。(不关心上次执行完的时间)

initialDelay、initialDelayString

第一次延迟多长时间后再执行

转载于:
Spring Boot 定时任务 -- @Scheduled
@Scheduled注解各参数详解

上一篇下一篇

猜你喜欢

热点阅读