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 }

 

posted @ 2018-01-10 17:43  穆晟铭  阅读(8161)  评论(0编辑  收藏  举报