日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網(wǎng)站首頁 編程語言 正文

SpringBoot之定時任務三種實現(xiàn)方法

作者:Mcband 更新時間: 2022-07-18 編程語言

SpringBoot創(chuàng)建定時任務,目前主要有以下三種實現(xiàn)方式:
一、基于注解(@Scheduled)
? 基于注解@Scheduled默認為單線程,開啟多個任務時,任務的執(zhí)行時機會受上一個任務執(zhí)行時間的影響;

二、基于接口(SchedulingConfigurer)
? 用于實現(xiàn)從數(shù)據(jù)庫獲取指定時間來動態(tài)執(zhí)行定時任務;

三、基于注解設定多線程定時任務
? 基于注解設定多線程定時任務;

一、靜態(tài):基于注解

使用SpringBoot基于注解來創(chuàng)建定時任務比較簡單,只需要如下代碼即可。 代碼如下:

@Configuration      //1.主要用于標記配置類,兼?zhèn)銫omponent的效果。
@EnableScheduling   // 2.開啟定時任務
public class SaticScheduleTask {
    //3.添加定時任務
    @Scheduled(cron = "0/5 * * * * ?")
    //或直接指定時間間隔,例如:5秒
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        System.err.println("執(zhí)行靜態(tài)定時任務時間: " + LocalDateTime.now());
    }
}

Cron表達式參數(shù)分別表示: 秒(0~59) 例如0/5表示每5秒 分(0~59) 時(0~23) 日(031)的某天,需計算月(011) 周幾( 可填1-7 或 SUN/MON/TUE/WED/THU/FRI/SAT)
@Scheduled:除了支持靈活的參數(shù)表達式cron之外,還支持簡單的延時操作,例如 fixedDelay ,fixedRate填寫相應的毫秒數(shù)即可。
建議:直接點擊在線Cron表達式生成器生成參數(shù)比較方便

啟動測試:
在這里插入圖片描述
顯然,使用@Scheduled
注解很方便,但缺點是當我們調(diào)整了執(zhí)行周期的時候,需要重啟應用才能生效,這多少有些不方便。為了達到實時生效的效果,可以使用接口來完成定時任務。

二、動態(tài):基于接口

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>

2、添加數(shù)據(jù)庫記錄:

DROP DATABASE IF EXISTS `socks`;
CREATE DATABASE `socks`;
USE `SOCKS`;
DROP TABLE IF EXISTS `cron`;
CREATE TABLE `cron`  (
  `cron_id` varchar(30) NOT NULL PRIMARY KEY,
  `cron` varchar(30) NOT NULL  
);
INSERT INTO `cron` VALUES ('1', '0/5 * * * * ?');

3、創(chuàng)建定時器
數(shù)據(jù)庫準備好數(shù)據(jù)后,開始編寫定時任務,注意這里添加的是TriggerTask,目的是循環(huán)讀取我們在數(shù)據(jù)庫設置好的執(zhí)行周期,以及執(zhí)行相關定時任務的內(nèi)容,具體代碼如下:

@Configuration      //1.主要用于標記配置類,兼?zhèn)銫omponent的效果。
@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;
     
    /**
     * 執(zhí)行定時任務.
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
     
        taskRegistrar.addTriggerTask(
                //1.添加任務內(nèi)容(Runnable)
                () -> System.out.println("執(zhí)行動態(tài)定時任務: " + LocalDateTime.now().toLocalTime()),
                //2.設置執(zhí)行周期(Trigger)
                triggerContext -> {
                    //2.1 從數(shù)據(jù)庫獲取執(zhí)行周期
                    String cron = cronMapper.getCron();
                    //2.2 合法性校驗.
                    if (StringUtils.isEmpty(cron)) {
                        // Omitted Code ..
                    }
                    //2.3 返回執(zhí)行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }

}

三、多線程定時任務

1.創(chuàng)建多線程定時任務

//@Component注解用于對那些比較中立的類進行注釋;
//相對與在持久層、業(yè)務層和控制層分別采用 @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();
    }
}

注:這里的@Async很重要
2、啟動測試
在這里插入圖片描述

原文鏈接:https://blog.csdn.net/mcband/article/details/125590094

欄目分類
最近更新