-
spring 定时任务
一、xml配置定时任务
1.定时任务命名空间的添加
task
2.定时任务方法代码
方法
3.配置
<task:scheduled-tasks>
<task:scheduled ref="taskSchedule" method="job1" cron="0/2 * * * * ?"/>
二、注解配置定时任务
1.定时任务命名空间的添加
task
2.配置定时任务驱动
<task:annotation-driven />
2.定时任务方法代码
@Scheduled(cron="0/2 * * * * ?")
三、Cron表达式
关于cronExpression 表达式有至少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)
常用符号
*
任意
-
范围
/
增加幅度
,
几个并列的值
?
不确定值
L和W
每月最后一天
#
第几
举例
"0 15 10 * * ? *"每天早上10:15 触发
"0 15 10 * * ? 2005" 2005 年的每天早上10:15 触发
"0 * 14 * * ?"每天从下午2 点开始到2 点59 分每分钟一次触发
"0 0/5 14 * * ?"每天从下午2 点开始到2:55 分结束每5 分钟一次触发
"0 15 10 15 * ?"每月15 号的10:15 触发
下面我们来实现每隔两秒打印一次hello world的题目:
第一步:在spring配置文件中定义task命名空间
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd
第二步:
①选择xml配置方式:
<task:scheduled-tasks>
<task:scheduled ref="taskJob" method="job01" cron="0/2 * * * * ?"/>
</task:scheduled-tasks>
②选择注解方式:
<!--注解task-->
<task:annotation-driven/>
第三步:实现
@Component
public class TaskJob {
// @Scheduled(cron = "0/2 * * * * ? ") //使用xml配置不需要,使用注解需要
public void job01() {
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "hello world");
}
}
第四步:测试类
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
}
打印结果: