spring进阶教程(三):定时任务

前言

前几节我们用第三方框架quarz实现了定时任务,实际上spring3.1开始,spring已经内置了定时任务的支持,实现非常简单,下面我们一起看看怎么实现

参考项目:https://github.com/bigbeef/cppba-sample
开源地址:https://github.com/bigbeef
个人博客:http://blog.cppba.com

ScheduleApplication.java

其中重点是@EnableScheduling注解,表示启动定时任务支持

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.cppba;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class ScheduleApplication {
public static void main(String[] args) {
SpringApplication.run(ScheduleApplication.class, args);
}
}

SaySchedule.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.cppba.schedule;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class SaySchedule {

private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

@Scheduled(cron = "0/2 * * * * ?")
public void sayHi() {
System.out.println("hi! time is :" + df.format(new Date()));
}

@Scheduled(cron = "1/2 * * * * ?")
public void sayHello() {
System.out.println("hello! time is :" + df.format(new Date()));
}
}

核心重点是@Scheduled注解,@Scheduled支持多种类型的计划任务:cron、fixDelay、fixRate,最流行的还是cron表达式,
在这里推荐一个cron表达式在线生成器:http://cron.qqe2.com/

功能很强大,可以图形化配置cron表达式,也可以泛解析cron表达式的执行时间,特别方便

运行项目

控制台打印如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
hi!    time is :2017-08-22 22:40:08
hello! time is :2017-08-22 22:40:09
hi! time is :2017-08-22 22:40:10
hello! time is :2017-08-22 22:40:11
hi! time is :2017-08-22 22:40:12
hello! time is :2017-08-22 22:40:13
hi! time is :2017-08-22 22:40:14
hello! time is :2017-08-22 22:40:15
hi! time is :2017-08-22 22:40:16
hello! time is :2017-08-22 22:40:17
hi! time is :2017-08-22 22:40:18
hello! time is :2017-08-22 22:40:19
hi! time is :2017-08-22 22:40:20
hello! time is :2017-08-22 22:40:21
hi! time is :2017-08-22 22:40:22
hello! time is :2017-08-22 22:40:23
hi! time is :2017-08-22 22:40:24

hello和hi交替执行,因为我们配置的cron表达式是:sayHi方法从0秒开始,每两秒执行一次;sayHello方法从1秒开始,每两秒执行一次。

到此,我们的定时任务运行成功!