spring boot: @EnableScheduling開啟計划任務支持,@Scheduled計划任務聲明


spring boot:

@EnableScheduling開啟計划任務支持,

@Scheduled計划任務聲明

 1 package ch2.scheduler2;
 2 
 3 //日期轉換方式
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 
 7 //計划任務聲明
 8 import org.springframework.scheduling.annotation.Scheduled;
 9 //spring組件注解
10 import org.springframework.stereotype.Service;
11 
12 @Service
13 public class SchedulerService {
14 
15     private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH::mm::ss");
16     
17     @Scheduled(fixedRate=5000)
18     public void proFixCurrentTime()
19     {
20         System.out.println("每5秒鍾執行一次:" + dateFormat.format(new Date()));
21     }
22     
23     @Scheduled(cron="0 53 18 ? * *")
24     public void cornCurrentTime()
25     {
26         System.out.println("自定執行時間: " + dateFormat.format(new Date()));
27     }
28     
29     
30 }

 

 1 package ch2.scheduler2;
 2 
 3 //引入spring配置注解
 4 import org.springframework.context.annotation.Configuration;
 5 //引入spring自動載入注解
 6 import org.springframework.context.annotation.ComponentScan;
 7 
 8 //計划任務聲明類:開啟計划任務聲明
 9 import org.springframework.scheduling.annotation.EnableScheduling;
10 
11 //spring配置類聲明
12 @Configuration
13 //自動引入當前包下的service,component....
14 @ComponentScan("ch2.scheduler2")
15 //開啟對計划任務的支持
16 @EnableScheduling
17 public class TaskSchedulerConfig {
18 
19 }

 

 1 package ch2.scheduler2;
 2 //引入容器
 3 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
 4 
 5 public class Main {
 6 
 7     public static void main(String[] args)
 8     {
 9         
10         AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class);
11         //SchedulerService schedulerService = context.getBean(SchedulerService.class);
12         
13     }
14     
15 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM