SpringCloud+Vue在线教育项目——整合定时任务
文章目录
前言:什么是定时任务(计划任务)?
这是百度解释:
计划任务,是任务在约定的时间执行已经计划好的工作,这是表面的意思。在Linux中,我们经常用到 cron
服务器来完成这项工作。cron服务器可以根据配置文件约定的时间来执行特定的任务。
转载大神解释:https://www.cnblogs.com/junrong624/p/4239517.html
Cron表达式是一个字符串,字符串以5或6个空格隔开,分为6或7个域,每一个域代表一个含义,Cron有如下两种语法格式:
Seconds Minutes Hours DayofMonth Month DayofWeek Year
或Seconds Minutes Hours DayofMonth Month DayofWeek
每一个域可出现的字符如下:
Seconds
:可出现", - * /“四个字符,有效范围为0-59的整数
Minutes
:可出现”, - * /“四个字符,有效范围为0-59的整数
Hours:
可出现”, - * /“四个字符,有效范围为0-23的整数
DayofMonth:
可出现”, - * / ? L W C"八个字符,有效范围为0-31的整数
Month
:可出现", - * /“四个字符,有效范围为1-12的整数或JAN-DEc
DayofWeek
:可出现”, - * / ? L C #“四个字符,有效范围为1-7的整数或SUN-SAT
两个范围。1表示星期天,2表示星期一, 依次类推
Year
:可出现”, - * /"四个字符,有效范围为1970-2099年
注意:springboot默认只支持6位,默认年位当前年
测试定时任务
第一步:在启动类上加上@EnableScheduling 注解
这个注解的完整路径是org.springframework.scheduling.annotation.EnableScheduling
@SpringBootApplication
@ComponentScan(basePackages = {"com.atguigu"})
@EnableDiscoveryClient
@EnableFeignClients
@MapperScan("com.atguigu.staservice.mapper")
@EnableScheduling//开启定时任务
public class StatisticApplication {
public static void main(String[] args) {
SpringApplication.run(StatisticApplication.class, args);
}
}
第二步:写定时任务类,加上@Component注解交给spring管理
@Component
public class ScheduleTask {
//"0/5 * * * * ?"
//每隔5秒执行一次该方法
@Scheduled(cron = "0/5 * * * * ?")
public void task(){
System.out.println("定时任务执行了!");
}
}
控制台输出:
定时任务执行了!
定时任务执行了!
定时任务执行了!
定时任务执行了!
定时任务执行了!
定时任务执行了!
定时任务执行了!
定时任务执行了!
定时任务执行了!
定时任务执行了!
定时任务执行了!
改造定时任务
第一步:使用在线cron表达式生成器生成表达式
在线cron表达式生成器:
http://cron.qqe2.com/
可以看到,选择任意的秒、分钟、小时、日、月、周、年能自动生成cron表达式。
项目需求:每天1点执行定时任务,econ表达式为: 0 0 1 * * ?
第二步:完善定时任务
项目需求:每天凌晨1点执行一次统计前一天的注册人数
@Component
public class ScheduleTask {
@Autowired
private StatisticsDailyService service;
//"0/5 * * * * ?"
//每天1点执行一次
/**
* cron表达式
* 计划任务,是任务在约定的时间执行已经计划好的工作,这是表面的意思。
* 在Linux中,我们经常用到 cron 服务器来完成这项工作。cron服务器可以根据配置文件约定的时间来执行特定的任务。
**/
//每天凌晨1点把前一天的数据统计一次
@Scheduled(cron = "0 0 1 * * ? ")
public void task(){
String yesterday = LocalDate.now().minusDays(1).toString();
service.countRegister(yesterday);
}
}