spring boot启动定时任务

1、

定时任务在Spring Boot中的集成

在启动类中加入开启定时任务的注解:

在SpringBoot中使用定时任务相当的简单。首先,我们在启动类中加入@EnableScheduling来开启定时任务。

@EnableScheduling
public class StartApplication {
    
    public static void main(String[] args) {        
        SpringApplication.run(StartApplication.class, args);
    }
}

2、然后我们直接创建执行定时任务的service即可,例如:

@Service
public class TestService {
    
    //每分钟启动一次
    @Scheduled(cron="0 0/1 * * * ?")
    public void test() {
        System.out.println("I am testing schedule");
    }

}

运行结果:

可以看到,已经每分钟执行一次该方法了

接下来:

我们讨论一下cron表达式:可以参考这篇文章:https://www.cnblogs.com/javahr/p/8318728.html

 除了上面那种方式,还可以指定fixedRate,fixedDelay,initialDelay等方式设置定时方式,如:

package com.zlc.service;

import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
public class TestService {
    
    //每分钟启动一次
    @Scheduled(cron="0/5 * * * * ?")
    public void test() {
        System.out.println("I am testing schedule");
    }
  
    //上一次启动时间点之后 每5秒执行一次
    @Scheduled(fixedRate= 5000)
    public void test1() {
        System.out.println("qd: "+new Date());
    }
    
    //上一次结束时间点之后 每5秒执行一次
    @Scheduled(fixedDelay = 5000)
    public void test2() {
        System.out.println("js: "+new Date());
    }
    
    //第一次延迟 X秒执行,之后按照fixedRate的规则每X秒执行
    @Scheduled(initialDelay = 5000,fixedRate = 6000)
    public void test3() {
        System.out.println("sdsds");
    }
    
}

猜你喜欢

转载自www.cnblogs.com/zlingchao/p/9574657.html
今日推荐