从Spring3.1开始,计划任务在Spring中的实现变得异常的简单。首先通过在配置类注解@EnableScheduling来开启对计划任务的支持,然后在要执行计划任务的方法上注解@Scheduled,声明这是一个计划任务。
Spring通过@Scheduled支持多种类型的计划任务,包含cron、fixDelay、fixRate等。
所以下面按照惯例,一个小demo
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/**
* 计划任务执行类
* @author zhangzhen
*
*/
@Service
public class ScheduledTaskService {
private static final SimpleDateFormat dateFormat = new
SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000) //声明该方法是计划任务,使用fixedRate属性每隔固定时间执行
public void reportCurrentTime() {
System.out.println("每隔五秒执行一次 " + dateFormat.format(new Date()));
}
//使用cron属性可按照指定时间执行,本例指的是每天11点28分执行;cron是UNIX和类UNIX(Linux)系统下的定时任务
@Scheduled(cron = "0 28 11 ? * *" )
public void fixTimeExecution() {
System.out.println("在指定时间 " + dateFormat.format(new Date()) + " 执行 ");
}
}
配置类
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
/**
* 通过@EnableScheduling注解开启对计划任务的支持
* @author zhangzhen
*
*/
@Configuration
@ComponentScan("com.spring.scheduled")
@EnableScheduling
public class TaskSchedulerConfig {
}
运行类
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* 跑一下的类
* @author zhangzhen
*
*/
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context =
new
AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
}
}
运行一下:
每隔五秒执行一次 16:10:45
每隔五秒执行一次 16:10:50
每隔五秒执行一次 16:10:55
每隔五秒执行一次 16:11:00
每隔五秒执行一次 16:11:05