1、介绍
Spring Task,可以把它看成轻量级的 Quartz,使用简单方便,也同样支持注解和配置文件两种形式,除此之外,还会额外介绍一种方式:通过前台操作调用 RESTful 执行定时任务的调度,下面,我将分别介绍。
2、定时任务开发步骤
2.1 基于配置文件
- 编写配置文件
package com.hafiz.www.cron;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Desc:第一个基于SpringTask的调度任务
*/
public class FirstCron {
private static final Logger logger = LoggerFactory.getLogger(FirstCron.class);
public void cron() {
logger.info("定时任务进行中.......");
// do something else
}
}
- 在 Spring 的配置文件头中添加命名空间及描述并配置定时任务
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<bean id="firstCron" class="com.hafiz.www.cron.FirstCron"/>
<task:scheduled-tasks>
<task:scheduled ref="firstCron" method="cron" cron="0/5 * * * * ?"/>
</task:scheduled-tasks>
</beans>
设置每 5 秒钟执行一次。
2.2 基于注解
我们可以使用 @Scheduled 注解进行开发,首先看下,该注解的源码:
package org.springframework.scheduling.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.scheduling.annotation.Schedules;
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(Schedules.class)
public @interface Scheduled {
String cron() default "";
String zone() default "";
long fixedDelay() default -1L;
String fixedDelayString() default "";
long fixedRate() default -1L;
String fixedRateString() default "";
long initialDelay() default -1L;
String initialDelayString() default "";
}
该注解有 5 个参数,分别表示的意思是:
- cron:指定cron表达式
- zone:官方文档解释:A time zone for which the cron expression will be resolved。指定cron表达式运行的时区
- fixedDelay:官方文档解释:An interval-based trigger where the interval is measured from the completion time of the previous task. The time unit value is measured in milliseconds.即表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒。
- fixedRate:官方文档解释:An interval-based trigger where the interval is measured from the start time of the previous task. The time unit value is measured in milliseconds.即从上一个任务开始到下一个任务开始的间隔,单位是毫秒。
- initialDelay:官方文档解释:Number of milliseconds to delay before the first execution of a fixedRate() or fixedDelay() task.任务第一次被调用前的延时,单位毫秒
- 编写定时任务类
package com.hafiz.www.cron;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Desc:第一个基于SpringTask的调度任务
*/
public class FirstCron {
private static final Logger logger = LoggerFactory.getLogger(FirstCron.class);
@Scheduled(cron = "0/5 * * * * ?")
public void cron() {
logger.info("定时任务进行中.......");
// do something else
}
}
- 在配置文件中添加
<task:annotation-driven/>
完成这两步即可。
2.3 通过调用 RESTful 执行定时任务的调度,使用一下 Controller 即可。
package com.louis.merak.common.schedule;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MerakTaskSchedulerController {
@Autowired
MerakTaskScheduler taskScheduler;
@RequestMapping("/schedule")
public String schedule(@RequestParam String cron) {
if(cron == null) {
cron = "0/5 * * * * *";
}
Runnable runnable = new Runnable() {
public void run() {
String time = new SimpleDateFormat("yy-MM-dd HH:mm:ss").format(new Date());
System.out.println("Test GETaskScheduler Success at " + time);
}
};
taskScheduler.schedule(runnable, cron);
return "Test TaskScheduler Interface.";
}
}