javaEE颠覆者第三章
3.3 定时任务
从spring3.1开始,定时任务在spring实现变得异常简单。用@EnableScheduling来开启支持,在要执行定时任务的方法上加上注解@Scheduled进行声明
(1)定时任务执行类
package spring4.taskscheduler;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Service
//@EnableScheduling //也可在方法本身开启 与配置类等价
public class ScheduledTaskService {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//@Scheduled(fixedRate = 5000) //使用@Scheduled声明该方法是计划(定时)任务 使用fixedRate规定每隔多少时间运行(单位是毫秒)
public void reportCurrentTime() {
System.out.println("每隔五秒执行一次 "+dateFormat.format(new Date()));
}
@Scheduled(cron = "00 10 11 ? * *") //使用cron属性按照指定时间执行 本例指的是 每天的11点08分执行一次
public void fixTimeExecution() {
System.out.println("在指定时间 "+dateFormat.format(new Date())+" 执行");
}
}
(2)配置类
package spring4.taskscheduler;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
@Configuration
@ComponentScan("spring4.taskscheduler")
@EnableScheduling //开启对计划任务的支持
public class TaskSchedulerConfig {
}
(3)运行
package spring4.taskscheduler;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class Main {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
ScheduledTaskService scheduledTaskService = context.getBean(ScheduledTaskService.class);
}
}
结果