定时任务概述
- 开发定时任务有三种实现方式
- 1:JDK 自带Timer(过于简单,功能不够)
- 2:第三方组件Quartz(过于强大,笨重)
- 3:Spring Task (功能强大,简单易用,支持xml和注解)
定时任务实现
xml配置
- 创建项目,添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task
https://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="task"/>
<task:scheduled-tasks>
<task:scheduled ref="taskJob" method="jojb1" cron="0/2 * * * * ?"/>
<task:scheduled ref="taskJob" method="job2" cron="0/5 * * * * ?"/>
</task:scheduled-tasks>
</beans>
注解配置
- @Scheduled (在方法上)
package task.job;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
@Component
public class TaskJob2 {
@Scheduled(cron = "0/2 * * * * ?")
public void jojb1(){
System.out.println("任务1"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
@Scheduled(cron = "0/5 * * * * ?")
public void job2(){
System.out.println("任务2"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
cron表达式
cron 表达式有至少6个(或 7 个)由空格分割的时间元素,从左至右,定义:
1:秒(0-59)
2:分钟(0-59)
3:小时(0-23)
4: 月份中的日期(1-31)
5:月份(1-12 或 JAN - DEC)
6:星期中的日期(1-7 或sun - sat)
7:年份(1970-2099)
[注]:
在线cron 表达式通过勾选方式生成满足的。