Spring Task定时任务
概述
在项目中开发中,定时任务是一种比较常见的需求,在Java中开发定时任务主要有三种解决方案:
- 使用JDK自带的Timer:Timer是JDK自带的定时任务工具,其简单易用,但是对于复杂的定时规则无法满足,在实际项目开发中也很少使用到。
- 使用第三方组件Quartz:Quartz功能强大,但是使用起来相对笨重。
- 使用Spring Task:而Spring Task则具备前两者的优点,功能强大且简单易用,除Spring相关的包外不需要额外的包,而且支持注解和配置文件两种形式。
通过配置文件使用Spring Task
我们先定义一个任务类MyTask
,如下
@Component
public class MyTask {
// 定时任务
public void job(){
System.out.println("执行任务:" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}
}
在配置文件中引入task的命名空间和规范,并定义定时规则,如下
<?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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<!-- 扫描器 -->
<context:component-scan base-package="org.example"/>
<!-- 定义定时规则 -->
<task:scheduled-tasks>
<!-- 每两秒执行一次 -->
<task:scheduled ref="myTask" method="job" cron="0/2 * * * * ?"/>
</task:scheduled-tasks>
</beans>
直接创建Spring的上下文环境即可,如下
public static void main(String[] args) {
// 创建Spring的上下文环境(Spring IOC 容器),并负责实例化,配置和组装Bean
ApplicationContext ac = new ClassPathXmlApplicationContext("spring.xml");
}
运行之后可以发现,每个两秒就调用一次job
。
通过注解使用Spring Task
通过注解使用Spring Task,我们需要先配置定时任务驱动,同样需要引入task命名空间,如下
<!-- 配置定时任务驱动。开启这个配置, spring才能识别@Scheduled注解 -->
<task:annotation-driven/>
接下来只需要在任务前加上Scheduled
注解即可,如下
@Component
public class MyTask {
// 定时任务,每两秒执行一次
@Scheduled(cron = "0/2 * * * * ?")
public void job(){
System.out.println("执行任务:" + new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
}
}
Cron表达式
由至少6个字段组成,也有可能是七个,字段间用空格隔开,一个字段内若由多个值可以用,
,各个字段含义如下
- 秒(0-59)
- 分钟(0-59)
- 小时(0-23)
- 日期(1-31)
- 月份(1-12或JAN-DEC)
- 周几(1-7或SUN-SAT),周几的1表示周日,因为周日是一周的第一天
- 年份(1970-2099),年份为可选字段
常用字符如下:
*
:可用在任意字段,表示该字段的任意时间?
:只能用在日期和周几字段上,表示不明确的值,例如想在每月的20日触发调度,不管20日到底是星期几,则只能使用如下写法:0 0 0 20 * ?
, 其中最后一位只能用?
,而不能使用*
,如果使用*
表示不管星期几都会触发。-
:可用在任意字段,表示一个范围,例如小时字段的0-12
表示0点-12点/
:可用在任意字段,表示起始/增幅,例如在秒字段的5/15
表示第5、20、35、50秒