项目开发中需要执行一些定时任务,比如需要在每天凌晨时候,分析一次前一天的日志信息之类的。平时使用Quartz比较多,但配置相对麻烦一点。今天就来说说Spring自带的定时任务。
Spring自带实现定时任务有两种方式,一种是通过注解的方式实现,一种是通过在配置文件中配置后实现。
一、通过spring的注解( @Scheduled)实现定时任务。
首先当然是Springde 配置:
第一步:添加这三段:
xmlns:task="http://www.springframework.org/schema/task"
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd
第二步:开启Spring定时器注解开关
<task:annotation-driven />
第三步:编写定时任务类和其中的方法,并为类和方法(可以有多个方法)添加注解。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import
java.text.SimpleDateFormat;
import
java.util.Date;
import
org.springframework.context.annotation.Lazy;
import
org.springframework.scheduling.annotation.Scheduled;
import
org.springframework.stereotype.Component;
@Component
(
"scheduledManager"
)
@Lazy
(value=
false
)
public
class
ScheduledManager {
public
static
SimpleDateFormat simpleDateFormat =
new
SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss"
);
//任务一
@Scheduled
(cron =
"0/5 * * * * ?"
)
public
void
autoCardCalculate() {
System.out.println(simpleDateFormat.format(
new
Date()) +
" :执行中任务1……"
);
}
//任务二
@Scheduled
(cron =
"0/5 * * * * ?"
)
public
void
autoCardCalculate2() {
System.out.println(simpleDateFormat.format(
new
Date()) +
" :执行中任务2……"
);
}
}
|
第四步:启动服务,效果立竿见影
+++++++++++++++++++++++++++以上便是通过注解的方式实现定时任务的+++++++++++++++++++++++++
++++++++++++++++下面便是通过在spring配置文件中配置的方式实现定时任务+++++++++++++++++++++
二、通过spring的配置文件实现定时任务。
与注解方式不同的是,定时任务的时间控制不是在注解中控制的,而是在配置文件中控制。
即在spring的配置文件中配置下面这段,代码中就不需要 @Scheduled 这个注解了。
1
2
3
4
5
|
<task:scheduled-tasks scheduler=
"myScheduler"
>
<task:scheduled ref=
"scheduledManager"
method=
"autoCardCalculate"
cron=
"0/5 * * * * *"
/>
<task:scheduled ref=
"scheduledManager"
method=
"autoCardCalculate2"
cron=
"1/5 * * * * *"
/>
</task:scheduled-tasks>
<task:scheduler id=
"myScheduler"
pool-size=
"10"
/>
|
唯一需要注意的就是定时任务类中的@Lazy(vlaue=false),这个注解,这个是懒加载的注解,可以不写,但是如果把value改为true,定时任务是不会执行的。因为加上之后,spring容器初始化的时候就不会触发这个定时任务了。
剩下的就是corn表达式了、具体使用以及参数请百度google、
下面只例出几个式子
CRON表达式 含义
"0 0 12 * * ?" 每天中午十二点触发
"0 15 10 ? * *" 每天早上10:15触发
"0 15 10 * * ?" 每天早上10:15触发
"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 0/5 14,18 * * ?" 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
"0 0-5 14 * * ?" 每天14:00至14:05每分钟一次触发
"0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44触发
"0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10:15触发