首页 > 技术文章 > springboot实现定时任务的一种方式

moly 2017-12-04 18:06 原文

参考:https://www.yoodb.com/news/detail/1205

目前觉得这种还是很好用,所以就记录。

最好新建一个项目测试:

1. pom中添加
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-task-core</artifactId>
        </dependency>            
2. 启动类添加注释:@EnableScheduling
3. 配置
server:
  port: 55550

#日志
logging:
  file: ./logs/apple.log

spring: 
  application: 
    name: asfood-apple

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:55580/eureka/

#详情[parent/asfood]/doc_nn/cron.txt
tasktime_cron: 0/20 * 14,15 * * ?

4. 新建类

@Configuration
public class TaskTest {
    private static int i = 0;
    
    /**
    cron:指定cron表达式。
    fixedDelay:
        官方文档解释:An interval-based trigger where the interval is measured from the completion time of the previous task. 
        The time unit value is measured in milliseconds.
        即表示从上一个任务完成开始到下一个任务开始的间隔,单位是毫秒。
    fixedRate:
        官方文档解释:An interval-based trigger where the interval is measured from the start time of the previous task. 
        The time unit value is measured in milliseconds.
        即从上一个任务开始到下一个任务开始的间隔,单位是毫秒。
     */
    @Scheduled(cron="${tasktime_cron}")
//    @Scheduled(fixedRate=2000) // 每5分钟执行一次   5*60*1000
//    @Scheduled(fixedRate=1000) // 每1s
    public void dual() {
        System.out.println(i++);
    }
}

运行,试试? 哈哈哈,估计可以成功,里面没什么多的东西,至于cron表达式可以百度学习。

 

推荐阅读