SpringBoot---(15)Spring Boot创建定时任务

摘要:项目中经常会需要做一些定时的跑的事情,比如每间隔多久做个统计,发个邮件,清理个数据。这时候就要用到定时任务,SpringBoot中,创建定时任务非常简单,具体步骤如下:

1.开启定时任务

在程序的入口类中添加@EnableScheduling注解

[java]   view plain  copy
  1. package com.alibaba;  
  2.   
  3. import org.mybatis.spring.annotation.MapperScan;  
  4. import org.springframework.boot.SpringApplication;  
  5. import org.springframework.boot.autoconfigure.SpringBootApplication;  
  6. import org.springframework.cache.annotation.EnableCaching;  
  7. import org.springframework.scheduling.annotation.EnableAsync;  
  8. import org.springframework.scheduling.annotation.EnableScheduling;  
  9. import org.springframework.web.bind.annotation.RequestMapping;  
  10. import org.springframework.web.bind.annotation.RequestMethod;  
  11. import org.springframework.web.bind.annotation.RestController;  
  12.   
  13. /** 
  14.  * the entrance of the application 
  15.  */  
  16. @EnableAsync  
  17. @RestController  
  18. @SpringBootApplication  
  19. @EnableCaching  
  20. @EnableScheduling  
  21. //扫描dao  
  22. @MapperScan("com.alibaba.dao")  
  23. public class TmallApplication {  
  24.   
  25.     public static void main(String[] args) {  
  26.         SpringApplication.run(TmallApplication.class, args);  
  27.     }  
  28.   
  29.     @RequestMapping(value = "hello",method = RequestMethod.GET)  
  30.     public String getHello(){  
  31.         return "hello world";  
  32.     }  

2.创建建定时任务

单独创建一个类,用来存放定时任务,然后在每个定时任务方法上,用注解标明定时任务的执行周期。我这里以每间隔10秒打印一下当前系统时间为例。

[java]   view plain  copy
  1. package com.alibaba.task;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.scheduling.annotation.Scheduled;  
  6. import org.springframework.stereotype.Component;  
  7.   
  8. /** 
  9.  * Created by lightClouds917 
  10.  * Date 2018/2/6 
  11.  * Description:定时任务 
  12.  */  
  13. @Component  
  14. public class ScheduledTask {  
  15.     private final Logger logger = LoggerFactory.getLogger(getClass());  
  16.   
  17.     /** 
  18.      * 每间隔10秒输出时间 
  19.      */  
  20.     @Scheduled(fixedRate = 10000)  
  21.     public void logTime(){  
  22.         logger.info("定时任务,现在时间:"+System.currentTimeMillis());  
  23.   
  24.     }  

3.@Scheduled的几种用法

@Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
@Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
@Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
@Scheduled(cron="*/5 * * * * *") :通过cron表达式定义规则
注意,这里的时间,单位是毫秒,1秒=1000毫秒

4.运行项目

猜你喜欢

转载自blog.csdn.net/tiantangdizhibuxiang/article/details/80530348