1. 程式人生 > >spring boot啟動定時任務

spring boot啟動定時任務

spring logs 例如 info 一次 work frame mage http

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"); } }

spring boot啟動定時任務