springBoot中定时任务的使用
cron表达式讲解
/**
* cron 知识讲解:
* cron 每位的含义:
* - 第一位,表示秒,取值 0-59;
* - 第二位,表示分,取值 0-59;
* - 第三位,表示小时,取值 0-23;
* - 第四位,日期天/日,取值 1-31;
* - 第五位,日期月份,取值 1-12;
* - 第六位,星期,取值 1-7,星期一、星期二…;注:不是第1周、第2周的意思,另外:1表示星期天,2表示星期一。
* - 第七位,年份,可以留空,取值 1970-2099。
*
* cron 符号含义:
* (*)星号:可以理解为每的意思,每秒、每分、每天、每月、每年……。
* (?)问号:问号只能出现在日期和星期这两个位置,表示这个位置的值不确定,每天 12 点执行,所以第六位星期的位置是不需要关注的,就是不确定的值。同时,日期和星期是两个相互排斥的元素,通过问号来表明不指定值。
* (-)减号:表达一个范围,如在小时字段中使用“10-12”,则表示从 10~12 点,即 10、11、12。
* (,)逗号:表达一个列表值,如在星期字段中使用“1,2,4”,则表示星期天、星期一、星期三。
* (/)斜杠:如 x/y,x 是开始值,y 是步长,比如在第一位(秒) 0/15 就是,从 0 秒开始,每 15 秒,最后就是 0、15、30、45、60,另 * /y,等同于 0/y。
*
* 例子:
* 0 0 1 * * ? 每天 1 点执行。
* 0 5 1 * * ? 每天 1 点 5 分执行。
* 0-5 * * * * ? 每分钟的0/1/2/3/4/5 秒执行
* 0 5/10 1 * * ? 每天 1 点的 5 分、15 分、25 分、35 分、45 分、55 分这几个时间点执行。
* 0 5 1 ? * 1 每周星期天,1点5分 执行,注:1 表示星期天。
* 0 10 3 ? * 1#3 每个月的第 三 个星期,星期天执行,# 号只能出现在星期的位置。
*/
启动类配置
在启动类中需要加入@EnableScheduling注解,意思是开启定时任务。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* Author: zhangtao
* Description: springBoot schedule
*/
@SpringBootApplication
@EnableScheduling
public class ScheduleApp {
public static void main(String[] args) {
SpringApplication.run(ScheduleApp.class, args);
}
}
定时任务Demo
写两个定时任务demo,一个每五秒钟打印一次日志,一个每一秒钟打印一次日志
package com.yuce.demo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
@Slf4j
public class ScheduleTask {
//每隔五秒执行一次
@Scheduled(cron = "${scheduleTask.cron1}")
public void execute() {
log.info("write message.{}",System.currentTimeMillis());
}
//每隔一秒执行一次
@Scheduled(cron = "${scheduleTask.cron2}")
public void execute1() {
log.info("write word.{}",System.currentTimeMillis());
}
}
application.properties
scheduleTask.cron1 = "*/5 * * * * ?"
scheduleTask.cron2 = "*/1 * * * * ?"
由于有两个任务,如果只有一个线程执行,那么同时执行两个任务就达不到定时执行的效果,因此我们可以开一个容量为2的线程池分别去执行两个任务,可以增加一个配置类,实现SchedulingConfigurer的接口
package com.yuce.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import java.util.concurrent.Executors;
@Configuration
public class ScheduleConfig implements SchedulingConfigurer {
@Override
public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
taskRegistrar.setScheduler(Executors.newScheduledThreadPool(2));
}
}