spring boot 定时任务(单线程)

xiaoxiao2021-03-01  26

spring boot 中 pom 文件配置

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>

spring boot 启动类

@SpringBootApplication @EnableScheduling public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

定时任务

import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.config.ScheduledTask; import org.springframework.stereotype.Component; @Component public class ScheduledService { private static final Logger logger = LoggerFactory.getLogger(ScheduledTask.class); //单线程定时任务 @Scheduled(cron="0 0/1 * * * ?") public void one() { // 间隔2分钟,执行任务 Thread current = Thread.currentThread(); logger.info("ScheduledTest.executeFileDownLoadTask 定时任务1:"+current.getId()+ ",name:"+current.getName()); } @Scheduled(cron="0 0/2 * * * ?") public void two() { // 间隔2分钟,执行任务 Thread current = Thread.currentThread(); logger.info("ScheduledTest.executeFileDownLoadTask 定时任务1:"+current.getId()+ ",name:"+current.getName()); } }

 

cron表达式详解

0 0/2 * * * ?

第一位:秒 取值范围(0-59)

第二位:分 取值范围(0-59)

第三位:时 取值范围(0-23)

第四位:天 取值范围(0-31)

第五位:月 取值范围(0-11)

第六位: 星期 取值范围(1-7 1=SUN MON TUE WED THU FRI SAT)

第七位:年份 (1970-2099)

一个cron表达式可以有七位也可以有六位

每一位都有三种表达方式

第一种:10(直接写一个值)假如是第一位(第一位代表秒),每分钟的第10秒运行。

第二种:0/10表示每10秒钟运行一次

第三种:0-10表示每分钟的0-10秒,每秒运行一次

 

转载请注明原文地址: https://www.6miu.com/read-4050146.html

最新回复(0)