Spring注解之 @EnableScheduling计划任务注解
生活随笔
收集整理的這篇文章主要介紹了
Spring注解之 @EnableScheduling计划任务注解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
要實現計劃任務,首先通過在配置類注解@EnableScheduling來開啟對計劃任務的支持,
然后在要執行計劃任務的方法上注解@Scheduled,聲明這是一個計劃任務
示例:計劃任務執行類
在這個類中的方法上需要@Scheduled注解配合@EnableScheduling使用。
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:計劃任務執行類*/ @Service public 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())+" 執行");} }
配置類
通過@EnableScheduling注解開啟對計劃任務的支持
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);}
} 運行結果
轉載于:https://www.cnblogs.com/liaojie970/p/9009500.html
總結
以上是生活随笔為你收集整理的Spring注解之 @EnableScheduling计划任务注解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小时代中的火是怎么回事?谁能详细解释一下
- 下一篇: 建模与设计01