计划执行任务
当开发者在AppConfig类中使用@EnableScheduling注解,并在某个task中使用@Schedule注解,那么被@Schedule注解标注的方法就可以在指定时间自动执行。
示例:
package cn.hncu.p3.p3_taskscheduler;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Service;import java.text.SimpleDateFormat;import java.util.Date;/*** Created with IntelliJ IDEA.* User:* Date: 2016/11/22.* Time: 下午 10:25.* Explain:计划任务执行类*/@Servicepublic class ScheduledTaskService {private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");@Scheduled(fixedRate = 5000) //通过@Scheduled声明该方法是计划任务,使用fixedRate属性每隔固定时间执行public void reportCurrentTime(){System.out.println("每隔5秒执行一次 "+dateFormat.format(new Date()));}@Scheduled(cron = "0 07 20 ? * *" ) //使用cron属性可按照指定时间执行,本例指的是每天20点07分执行;//cron是UNIX和类UNIX(Linux)系统下的定时任务public void fixTimeExecution(){System.out.println("在指定时间 "+dateFormat.format(new Date())+" 执行");}}
package cn.hncu.p3.p3_taskscheduler;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.scheduling.annotation.EnableScheduling;/*** Created with IntelliJ IDEA.* User:* Date: 2016/11/22.* Time: 下午 10:32.* Explain:配置类*/@Configuration@ComponentScan("cn.hncu.p3.p3_taskscheduler")@EnableScheduling //通过@EnableScheduling注解开启对计划任务的支持public class TaskScheduleConfig {}
package cn.hncu.p3.p3_taskscheduler;import org.springframework.context.annotation.AnnotationConfigApplicationContext;/*** Created with IntelliJ IDEA.* User:* Date: 2016/11/22.* Time: 下午 10:34.* Explain:运行类*/public class Main {public static void main(String[] args) {AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskScheduleConfig.class);}}
运行结果
