1. 程式人生 > 程式設計 >Springboot非分散式定時任務實現程式碼

Springboot非分散式定時任務實現程式碼

1. 核心註解

在springboot專案中我們可以很方便地使用spring自己的註解@Scheduled和@EnableScheduling配合來實現便捷開發定時任務。

@EnableScheduling註解的作用是發現註解@Scheduled的任務並後臺執行,此註解可以加到啟動類上也可以加到執行排程任務類上。

經測試,當有多個包含定時任務的類時,@EnableScheduling註解加在其中一個類上就可以保證所有定時任務的成功實現。

注意:定時任務的類上還需要配合使用@Configuration或@Component註解,這兩個註解都可以。

2. 例項程式碼

2.1 @EnableScheduling加在啟動類上;

import com.my.common.util.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description:
 * @author: Karl
 * @date: 2020/10/10
 */
@Component
public class TestSchedule01 {

  @Scheduled(cron = "0 * * * * ? ")
  public void test() {
    System.out.println("我是定時任務01,我執行了" + DateUtil.formatDateByDateTime(new Date()));
  }
}

import com.my.common.util.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description:
 * @author: Karl
 * @date: 2020/10/10
 */
@Configuration
public class TestSchedule02 {

  @Scheduled(cron = "1 * * * * ? ")
  public void test() {
    System.out.println("我是定時任務02,我執行了" + DateUtil.formatDateByDateTime(new Date()));
  }
}

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@EnableScheduling
@SpringBootApplication
public class DemoApplication {

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

}

2.1 @EnableScheduling加在任務類上;

import com.my.common.util.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description:
 * @author: Karl
 * @date: 2020/10/10
 */
@Component
@EnableScheduling
public class TestSchedule01 {

  @Scheduled(cron = "0 * * * * ? ")
  public void test() {
    System.out.println("我是定時任務01,我執行了" + DateUtil.formatDateByDateTime(new Date()));
  }
}

import com.my.common.util.DateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description:
 * @author: Karl
 * @date: 2020/10/10
 */
@Configuration
public class TestSchedule02 {

  @Scheduled(cron = "1 * * * * ? ")
  public void test() {
    System.out.println("我是定時任務02,我執行了" + DateUtil.formatDateByDateTime(new Date()));
  }
}

注意:只需要在其中一個任務類上加上@EnableScheduling註解,所有的定時任務就都可以正常執行。

3. @Scheduled的幾種用法

@Scheduled這個註解支援3種定時方式,即:cron、fixedRate和fixedDelay

cron:是以表示式的形式來表示時間,最常見;

fixedRate:表示Scheduled隔多長時間呼叫一次,不管任務是否執行完;

fixedDelay:表示該任務執行完後隔多長時間再呼叫;

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。