springboot定時任務@Scheduled詳解


springboot之定時任務@Scheduled詳解 

1.使用SpringBoot創建定時任務非常簡單,目前主要有以下三種創建方式:

  • 一、基於注解(@Scheduled)
  • 二、基於接口(SchedulingConfigurer) 前者相信大家都很熟悉,但是實際使用中我們往往想從數據庫中讀取指定時間來動態執行定時任務,這時候基於接口的定時任務就派上用場了。
  • 三、基於注解設定多線程定時任務

一、靜態:基於注解

基於注解@Scheduled默認為單線程,開啟多個任務時,任務的執行時機會受上一個任務執行時間的影響。

1、創建定時器

使用SpringBoot基於注解來創建定時任務非常簡單,只需幾行代碼便可完成。 代碼如下:

 1 @Configuration      //1.主要用於標記配置類,兼備Component的效果。
 2 @EnableScheduling   // 2.開啟定時任務
 3 public class SaticScheduleTask {
 4     //3.添加定時任務
 5     @Scheduled(cron = "0/5 * * * * ?")
 6     //或直接指定時間間隔,例如:5秒
 7     //@Scheduled(fixedRate=5000)
 8     private void configureTasks() {
 9         System.err.println("執行靜態定時任務時間: " + LocalDateTime.now());
10     }
11 }
View Code

 

Cron表達式參數分別表示:

  • 秒(0~59) 例如0/5表示每5秒
  • 分(0~59)
  • 時(0~23)
  • 日(0~31)的某天,需計算
  • 月(0~11)
  • 周幾( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)

@Scheduled:除了支持靈活的參數表達式cron之外,還支持簡單的延時操作,例如 fixedDelay ,fixedRate 填寫相應的毫秒數即可。

// Cron表達式范例:

每隔5秒執行一次:*/5 * * * * ?

每隔1分鍾執行一次:0 */1 * * * ?

每天23點執行一次:0 0 23 * * ?

每天凌晨1點執行一次:0 0 1 * * ?

每月1號凌晨1點執行一次:0 0 1 1 * ?

每月最后一天23點執行一次:0 0 23 L * ?

每周星期天凌晨1點實行一次:0 0 1 ? * L

在26分、29分、33分執行一次:0 26,29,33 * * * ?

每天的0點、13點、18點、21點都執行一次:0 0 0,13,18,21 * * ?

二、動態:基於接口

基於接口(SchedulingConfigurer)

1、導入依賴包:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

    <dependencies>
        <dependency><!--添加Web依賴 -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency><!--添加MySql依賴 -->
             <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency><!--添加Mybatis依賴 配置mybatis的一些初始化的東西-->
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency><!-- 添加mybatis依賴 -->
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
View Code

 

然后在項目中的application.yml 添加數據源:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/socks
    username: root
    password: 123456
View Code

 

3、創建定時器

數據庫准備好數據之后,我們編寫定時任務,注意這里添加的是TriggerTask,目的是循環讀取我們在數據庫設置好的執行周期,以及執行相關定時任務的內容。
具體代碼如下:

@Configuration      //1.主要用於標記配置類,兼備Component的效果。
@EnableScheduling   // 2.開啟定時任務
public class DynamicScheduleTask implements SchedulingConfigurer {

    @Mapper
    public interface CronMapper {
        @Select("select cron from cron limit 1")
        public String getCron();
    }

    @Autowired      //注入mapper
    @SuppressWarnings("all")
    CronMapper cronMapper;

    /**
     * 執行定時任務.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        taskRegistrar.addTriggerTask(
                //1.添加任務內容(Runnable)
                () -> System.out.println("執行動態定時任務: " + LocalDateTime.now().toLocalTime()),
                //2.設置執行周期(Trigger)
                triggerContext -> {
                    //2.1 從數據庫獲取執行周期
                    String cron = cronMapper.getCron();
                    //2.2 合法性校驗.
                    if (StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                    }
                    //2.3 返回執行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }

}
View Code

 

注意: 如果在數據庫修改時格式出現錯誤,則定時任務會停止,即使重新修改正確;此時只能重新啟動項目才能恢復。

三、多線程定時任務

基於注解設定多線程定時任務

1、創建多線程定時任務

//@Component注解用於對那些比較中立的類進行注釋;
//相對與在持久層、業務層和控制層分別采用 @Repository、@Service 和 @Controller 對分層中的類進行注釋
@Component
@EnableScheduling   // 1.開啟定時任務
@EnableAsync        // 2.開啟多線程
public class MultithreadScheduleTask {

        @Async
        @Scheduled(fixedDelay = 1000)  //間隔1秒
        public void first() throws InterruptedException {
            System.out.println("第一個定時任務開始 : " + LocalDateTime.now().toLocalTime() + "\r\n線程 : " + Thread.currentThread().getName());
            System.out.println();
            Thread.sleep(1000 * 10);
        }

        @Async
        @Scheduled(fixedDelay = 2000)
        public void second() {
            System.out.println("第二個定時任務開始 : " + LocalDateTime.now().toLocalTime() + "\r\n線程 : " + Thread.currentThread().getName());
            System.out.println();
        }
    }
View Code

 

注:這里的@Async注解很關鍵(不受其他定時任務影響,可能會導致重復數據)


免責聲明!

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



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