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

學(xué)無(wú)先后,達(dá)者為師

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

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

作者:Mcband 更新時(shí)間: 2022-07-18 編程語(yǔ)言

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

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

三、基于注解設(shè)定多線程定時(shí)任務(wù)
? 基于注解設(shè)定多線程定時(shí)任務(wù);

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

使用SpringBoot基于注解來(lái)創(chuàng)建定時(shí)任務(wù)比較簡(jiǎn)單,只需要如下代碼即可。 代碼如下:

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

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

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

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

1.導(dǎo)入依賴

<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ù)庫(kù)記錄:

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í)器
數(shù)據(jù)庫(kù)準(zhǔn)備好數(shù)據(jù)后,開始編寫定時(shí)任務(wù),注意這里添加的是TriggerTask,目的是循環(huán)讀取我們?cè)跀?shù)據(jù)庫(kù)設(shè)置好的執(zhí)行周期,以及執(zhí)行相關(guān)定時(shí)任務(wù)的內(nèi)容,具體代碼如下:

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

}

三、多線程定時(shí)任務(wù)

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

//@Component注解用于對(duì)那些比較中立的類進(jìn)行注釋;
//相對(duì)與在持久層、業(yè)務(wù)層和控制層分別采用 @Repository、@Service 和 @Controller 對(duì)分層中的類進(jìn)行注釋
@Component
@EnableScheduling   // 1.開啟定時(shí)任務(wù)
@EnableAsync        // 2.開啟多線程
public class MultithreadScheduleTask {
    @Async
    @Scheduled(fixedDelay = 1000)  //間隔1秒
    public void first() throws InterruptedException {
        System.out.println("第一個(gè)定時(shí)任務(wù)開始 : " + 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("第二個(gè)定時(shí)任務(wù)開始 : " + LocalDateTime.now().toLocalTime() + "\r\n線程 : " + Thread.currentThread().getName());
        System.out.println();
    }
}

注:這里的@Async很重要
2、啟動(dòng)測(cè)試
在這里插入圖片描述

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

欄目分類
最近更新