springBoot自定的定时任务器Scheduled使用

一、cron的说明

  在方法上使用@Scheduled注解来设置任务的执行时间,并使用三种属性配置方式: fixedRate: 描述:每隔多少时间就启动任务,不管该任务是否启动完成。 执行时机:项目启动时及开始

fixedDelay: 描述:每次执行任务完成之后间隔多久再执行该任务 执行时机:项目启动即开始

配置文件中指定cron 加入application.yml中指定:custom.schedule.cron.task1: 0/5 *****

代码中可以这样写:@Scheduled(cron="$custom.schedule.cron.task1:0/10*****}")

  Cron表示式是一个字符串,字符串以5个或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下格式 ( 1) Seconds Minutes Hours DayofMonth Month DayofWeek Year

(2)Seconds Minutes Hours DayofMonth Month DayofWeek

1.1、结构如下:

corn从左到右(用空格隔开):秒 分 小时 月份中的日期 月份 星期中的日期 年份  各个字段的含义  字段 允许值 允许的特殊字符 秒(Seconds) 0~59的整数 , - * / 四个字符 分(Minutes) 0~59的整数 , - * / 四个字符 小时(Hours) 0~23的整数 , - * / 四个字符 日期(DayofMonth) 1~31的整数(但是你需要考虑你月的天数) ,- * ? / L W C 八个字符 月份(Month) 1~12的整数或者 JAN-DEC , - * / 四个字符 星期(DayofWeek) 1~7的整数或者 SUN-SAT (1=SUN) , - * ? / L C # 八个字符 年(可选,留空)(Year) 1970~2099 , - * / 四个字符

二、创建工程

添加spirngBoot依赖

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

启动定期器(主类添加EnableScheduling)

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

创建实现类

@Component
public class MyTest {

    @Scheduled(cron="0/5 * * * * *")
    public void scheduled1(){
        System.out.println("this is cron " + System.currentTimeMillis());
    }

    @Scheduled(fixedRate = 5000)
    public void scheduled2(){
        System.out.println("this is cron " + System.currentTimeMillis());
    }

    @Scheduled(fixedDelay = 5000)
    public void scheduled3(){
        System.out.println("this is cron " + System.currentTimeMillis());
    }
}

运行启动类,执行结果如下:

经验分享 程序员 微信小程序 职场和发展