Spring Boot 定時任務單線程和多線程

最近在寫springboot項目中一個數據轉移的組件,原本是用java中的timer和Executor實現java

能夠有個springboot測試時關閉單例工廠的現象。如今試一試spring本身的線程管理是否但是不包上面的錯誤spring

 

帖子中內容直接粘貼就能夠實現springboot

原貼鏈接已經附上多線程

Spring Boot 的定時任務:併發

第一種:把參數配置到.properties文件中:app

代碼:ide

 

 
  1. package com.accord.task;測試

  2.  
  3. import java.text.SimpleDateFormat;this

  4. import java.util.Date;spa

  5.  
  6. import org.springframework.scheduling.annotation.Scheduled;

  7. import org.springframework.stereotype.Component;

  8.  
  9. /**

  10. * 從配置文件加載任務信息

  11. * @author 王久印

  12. * 2018年3月1日

  13. */

  14. @Component

  15. public class ScheduledTask {

  16.  
  17. private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

  18.  
  19. //@Scheduled(fixedDelayString = "${jobs.fixedDelay}")

  20. @Scheduled(fixedDelayString = "2000")

  21. public void getTask1() {

  22. System.out.println("任務1,從配置文件加載任務信息,當前時間:" + dateFormat.format(new Date()));

  23. }

  24.  
  25. @Scheduled(cron = "${jobs.cron}")

  26. public void getTask2() {

  27. System.out.println("任務2,從配置文件加載任務信息,當前時間:" + dateFormat.format(new Date()));

  28. }

  29. }

application.properties文件:

 

 
  1. jobs.fixedDelay=5000

  2. jobs.cron=0/5 * * * * ?

SpringBootCron2Application.java中:

 

 
  1. package com.accord;

  2.  
  3. import org.springframework.boot.SpringApplication;

  4. import org.springframework.boot.autoconfigure.SpringBootApplication;

  5. import org.springframework.scheduling.annotation.EnableScheduling;

  6.  
  7. @SpringBootApplication

  8. @EnableScheduling

  9. public class SpringBootCron2Application {

  10. public static void main(String[] args) {

  11. SpringApplication.run(SpringBootCron2Application.class, args);

  12. }

  13. }

注:@EnableScheduling  這個必定要加上;不然,不會定時啓動任務!

@Scheduled中的參數說明:

 

 
  1. @Scheduled(fixedRate=2000):上一次開始執行時間點後2秒再次執行;

  2.  
  3. @Scheduled(fixedDelay=2000):上一次執行完畢時間點後2秒再次執行;

  4.  
  5. @Scheduled(initialDelay=1000, fixedDelay=2000):第一次延遲1秒執行,而後在上一次執行完畢時間點後2秒再次執行;

  6.  
  7. @Scheduled(cron="* * * * * ?"):按cron規則執行。

在線Cron表達式生成器:http://cron.qqe2.com/

 

第二種定時任務:單線程和多線程

一、建立定時任務:

 

 
  1. package com.accord.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. * 構建執行定時任務

  10. * @author 王久印

  11. * 2018年3月1日

  12. * TODO

  13. */

  14. @Component

  15. public class ScheduledTask2 {

  16.  
  17. private Logger logger = LoggerFactory.getLogger(ScheduledTask2.class);

  18.  
  19. private int fixedDelayCount = 1;

  20. private int fixedRateCount = 1;

  21. private int initialDelayCount = 1;

  22. private int cronCount = 1;

  23.  
  24. @Scheduled(fixedDelay = 5000) //fixedDelay = 5000表示當前方法執行完畢5000ms後,Spring scheduling會再次調用該方法

  25. public void testFixDelay() {

  26. logger.info("===fixedDelay: 第{}次執行方法", fixedDelayCount++);

  27. }

  28.  
  29. @Scheduled(fixedRate = 5000) //fixedRate = 5000表示當前方法開始執行5000ms後,Spring scheduling會再次調用該方法

  30. public void testFixedRate() {

  31. logger.info("===fixedRate: 第{}次執行方法", fixedRateCount++);

  32. }

  33.  
  34. @Scheduled(initialDelay = 1000, fixedRate = 5000) //initialDelay = 1000表示延遲1000ms執行第一次任務

  35. public void testInitialDelay() {

  36. logger.info("===initialDelay: 第{}次執行方法", initialDelayCount++);

  37. }

  38.  
  39. @Scheduled(cron = "0 0/1 * * * ?") //cron接受cron表達式,根據cron表達式肯定定時規則

  40. public void testCron() {

  41. logger.info("===initialDelay: 第{}次執行方法", cronCount++);

  42. }

  43.  
  44. }

使用 @Scheduled來建立定時任務 這個註解用來標註一個定時任務方法。 
經過看 @Scheduled源碼能夠看出它支持多種參數:
    (1)cron:cron表達式,指定任務在特定時間執行;
    (2)fixedDelay:表示上一次任務執行完成後多久再次執行,參數類型爲long,單位ms;
    (3)fixedDelayString:與fixedDelay含義同樣,只是參數類型變爲String;
    (4)fixedRate:表示按必定的頻率執行任務,參數類型爲long,單位ms;
    (5)fixedRateString: 與fixedRate的含義同樣,只是將參數類型變爲String;
    (6)initialDelay:表示延遲多久再第一次執行任務,參數類型爲long,單位ms;
    (7)initialDelayString:與initialDelay的含義同樣,只是將參數類型變爲String;
    (8)zone:時區,默認爲當前時區,通常沒有用到。

二、開啓定時任務:

 

 
  1. package com.accord;

  2.  
  3. import org.springframework.boot.SpringApplication;

  4. import org.springframework.boot.autoconfigure.SpringBootApplication;

  5. import org.springframework.scheduling.annotation.EnableScheduling;

  6.  
  7. @SpringBootApplication

  8. @EnableScheduling

  9. public class SpringBootCron2Application {

  10. public static void main(String[] args) {

  11. SpringApplication.run(SpringBootCron2Application.class, args);

  12. }

  13. }

注:這裏的 @EnableScheduling  註解,它的做用是發現註解 @Scheduled的任務並由後臺執行。沒有它的話將沒法執行定時任務。
引用官方文檔原文:
@EnableScheduling ensures that a background task executor is created. Without it, nothing gets scheduled.

三、執行結果(單線程)

就完成了一個簡單的定時任務模型,下面執行springBoot觀察執行結果:

從控制檯輸入的結果中咱們能夠看出全部的定時任務都是在同一個線程池用同一個線程來處理的,那麼咱們如何來併發的處理各定時任務呢,請繼續向下看。

四、多線程處理定時任務:

看到控制檯輸出的結果,全部的定時任務都是經過一個線程來處理的,我估計是在定時任務的配置中設定了一個SingleThreadScheduledExecutor,因而我看了源碼,從ScheduledAnnotationBeanPostProcessor類開始一路找下去。果真,在ScheduledTaskRegistrar(定時任務註冊類)中的ScheduleTasks中又這樣一段判斷:

 

 
  1. if (this.taskScheduler == null) {

  2. this.localExecutor = Executors.newSingleThreadScheduledExecutor();

  3. this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);

  4. }

這就說明若是taskScheduler爲空,那麼就給定時任務作了一個單線程的線程池,正好在這個類中還有一個設置taskScheduler的方法:

 

 
  1. public void setScheduler(Object scheduler) {

  2. Assert.notNull(scheduler, "Scheduler object must not be null");

  3. if (scheduler instanceof TaskScheduler) {

  4. this.taskScheduler = (TaskScheduler) scheduler;

  5. }

  6. else if (scheduler instanceof ScheduledExecutorService) {

  7. this.taskScheduler = new ConcurrentTaskScheduler(((ScheduledExecutorService) scheduler));

  8. }

  9. else {

  10. throw new IllegalArgumentException("Unsupported scheduler type: " + scheduler.getClass());

  11. }

  12. }

這樣問題就很簡單了,咱們只需用調用這個方法顯式的設置一個ScheduledExecutorService就能夠達到併發的效果了。咱們要作的僅僅是實現SchedulingConfigurer接口,重寫configureTasks方法就OK了;

package com.pingan.ph.cis.data.transfer.selfoperation;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import java.util.concurrent.Executors;


@Configuration
//全部的定時任務都放在一個線程池中,定時任務啓動時使用不一樣都線程。
public class ScheduleConfig implements SchedulingConfigurer {
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //設定一個長度10的定時任務線程池
        taskRegistrar.setScheduler(Executors.newScheduledThreadPool(10));
    }
}

 

五、執行結果(併發)

經過控制檯輸出的結果看出每一個定時任務都是在經過不一樣的線程來處理了。

相關文章
相關標籤/搜索