spring boot: 计划任务@ EnableScheduling和@Scheduled
@Scheduled中的参数说明
1 2 3 4 5 6 7 |
|
常用Cron表达式( 秒/分/时/日/月/周/年 )
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
实例:
service
1 package ch2.scheduler; 2 3 //时间处理,时间格式化 4 import java.util.Date; 5 import java.text.SimpleDateFormat; 6 7 8 //spring计划任务声明(针对方法声明) 9 import org.springframework.scheduling.annotation.Scheduled; 10 //spring组件声明 11 import org.springframework.stereotype.Service; 12 13 14 //组件什么 15 @Service 16 public class SchedulerService { 17 18 //创建日期模板 19 private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH::MM::ss"); 20 21 22 //每5秒钟执行一次 23 @Scheduled(fixedRate = 5000) 24 public void reportCurrentTime() 25 { 26 System.out.println("每五秒执行一次: " + dateFormat.format( new Date() )); 27 } 28 29 //按照cron属性指定执行时间:秒分时 30 @Scheduled(cron = "0 34 18 ? * *") 31 public void fixTimeExecution() 32 { 33 System.out.println("在指定的时间内执行: " + dateFormat.format( new Date()) ); 34 } 35 36 37 }
config
1 package ch2.scheduler; 2 3 //自动引入包 4 import org.springframework.context.annotation.ComponentScan; 5 //配置类声明 6 import org.springframework.context.annotation.Configuration; 7 8 //计划任务类声明 9 import org.springframework.scheduling.annotation.EnableScheduling; 10 11 12 //配置类声明 13 @Configuration 14 //自动引入包 15 @ComponentScan("ch2.scheduler") 16 //通过@EnableScheduling开启对计划任务的支持 17 @EnableScheduling 18 public class TaskSchedulerConfig { 19 20 21 22 }
main
1 package ch2.scheduler; 2 //引入容器 3 import org.springframework.context.annotation.AnnotationConfigApplicationContext; 4 5 public class Main { 6 7 8 public static void main(String[] args) 9 { 10 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TaskSchedulerConfig.class); 11 //SchedulerService schedulerService = context.getBean(SchedulerService.class); 12 13 14 } 15 }