spring @Scheduled定時任務使用說明及基本工作原理介紹


使用說明及工作原理:

package com.example.spring.async;

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

import com.example.spring.MyLog;
/**
 * 定時任務使用示例
 *  1.啟動類增加注解 @EnableScheduling
 *  2.相應類聲明為服務 @Service
 *  3.方法上面增加 @Scheduled, 指定不同的參數以不同的方式運行定時任務
 * 備注:
 *  @Scheduled中參數解釋:
 *      fixedRate:表示以固定的時間間隔執行(上次開始執行和本次開始執行之間的時間間隔),不關注被執行方法實際的執行時間
 *      fixedDelay:表示以固定的延遲執行(上次執行結束和本次開始執行的時間間隔),受被執行方法執行時間的影響
 *      cron="2 * * * * *": cron表達式配置執行方法。總共6位,分別代表 秒 分 時 日 月 周
 *  spring底層執行器:(默認使用的是單線程線程池)
 *      this.localExecutor = Executors.newSingleThreadScheduledExecutor();
 *      this.taskScheduler = new ConcurrentTaskScheduler(this.localExecutor);
 *  加載流程:
 *      ScheduledAnnotationBeanPostProcessor -> ScheduledTaskRegistrar -> afterPropertiesSet()
 *  @Scheduled 的方法必須是空返回值和無參方法,直接調用這個方法是同步的
 * @DESC 
 * @author guchuang
 *
 */
@Service
public class ScheduleMethod {
    
    public ScheduleMethod() {
        MyLog.info("-----------------------ScheduleMethod init--------------------------");
    }
    /*@Scheduled(fixedRate=2000)
    public void foo1() {
        MyLog.info("每2秒執行一次,不管上次執行完成時間,fixedRate=2000");
    }
    
    @Scheduled(fixedDelay=2000)
    public void foo2() {
        MyLog.info("上次執行完成,2s后執行,以此遞推,fixedDelay=2000");
    }*/
    
    @Scheduled(fixedRate=2000)
    public void foo3() {
        MyLog.info("每2秒執行一次,不管上次執行完成時間,fixedRate=2000");
        MyLog.sleep(1000);
    }
    
    /*@Scheduled(fixedDelay=10000)
    public void foo4() {
        //MyLog.info("上次執行完成,2s后執行,以此遞推,fixedDelay=3000");
        MyLog.info("上次執行完成,2s后執行,以此遞推,fixedDelay=3000 ----start");
        MyLog.sleep(1000);
        MyLog.info("上次執行完成,2s后執行,以此遞推,fixedDelay=3000 ----end");
    }*/
    
    @Scheduled(cron="*/2 * * * * *")
    public void foo5() {
        MyLog.info("cron test--每隔兩秒執行一次");
    }
}

配置類:

package com.example.spring.async.config;

import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;

import com.example.spring.MyThreadFactory;

@Configuration
public class ScheduleConfig implements SchedulingConfigurer{
    
    /**
     * 向spring容器注入TaskScheduler線程池,用於執行@Scheduled注解標注的方法.
     * 類型為TaskScheduler.class, name為taskExecutor1的bean(使用類型注入spring,不是bean name)
     * 如果沒有注入TaskScheduler或者ScheduledExecutorService,則默認使用單線程的線程池作為底層支撐
     * @return TaskScheduler 實例
     */
    @Bean
    public TaskScheduler taskExecutor() {
        return new ConcurrentTaskScheduler(Executors.newScheduledThreadPool(3, new MyThreadFactory("scheduled")));
    }
    
    @Bean
    @Qualifier("test-123")
    public TaskScheduler taskExecutor2() {
        return new ConcurrentTaskScheduler(Executors.newScheduledThreadPool(3, new MyThreadFactory("scheduled2")));
    }

    /**
     * 可以用於執行定時任務,設置taskScheduler等
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //taskRegistrar.setScheduler(taskExecutor1());      用於顯示的設置線程池執行器
        taskRegistrar.addFixedDelayTask(() -> System.out.println("SchedulingConfigurer test"), 5000);
    }
    
}

測試類

package com.example.spring.async;

import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import com.example.spring.BaseDemoApplicationTest;
import com.example.spring.MyLog;
import com.example.spring.async.ScheduleMethod;

public class ScheduleMethodTest extends BaseDemoApplicationTest {

    @Autowired
    ScheduleMethod schedule;
    
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    }

    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void test() {
        MyLog.sleep(1000 * 30);
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM