溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

如何使用spring-task定時(shí)任務(wù)動(dòng)態(tài)配置修改執(zhí)行時(shí)間

發(fā)布時(shí)間:2021-11-02 11:44:22 來(lái)源:億速云 閱讀:331 作者:小新 欄目:開(kāi)發(fā)技術(shù)

小編給大家分享一下如何使用spring-task定時(shí)任務(wù)動(dòng)態(tài)配置修改執(zhí)行時(shí)間,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

spring-task定時(shí)任務(wù)動(dòng)態(tài)配置修改執(zhí)行時(shí)間

因項(xiàng)目需要,幾個(gè)定時(shí)任務(wù)需要人為動(dòng)態(tài)設(shè)置執(zhí)行時(shí)間,于是乎吧,就查閱相關(guān)資料,是可以動(dòng)態(tài)設(shè)置的,廢話(huà)不多說(shuō),直接上代碼,一目了然。

package com.seckill.quartz;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
 
/**
 * Created by loup on 2017/11/11.
 */
@Component
@EnableScheduling
public class DynamicScheduledTask implements SchedulingConfigurer {
    //時(shí)間表達(dá)式  每2秒執(zhí)行一次
    private String cron = "0/2 * * * * ?";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                //任務(wù)邏輯
                System.out.println("---------------start-------------------");
                System.out.println("動(dòng)態(tài)修改定時(shí)任務(wù)參數(shù),時(shí)間表達(dá)式cron為:" + cron);
                System.out.println("當(dāng)前時(shí)間為:" + sdf.format(new Date()));
                System.out.println("----------------end--------------------");
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                CronTrigger cronTrigger = new CronTrigger(cron);
                Date nextExecDate = cronTrigger.nextExecutionTime(triggerContext);
                return nextExecDate;
            }
        });
    }
 
    public void setCron(String cron) {
        this.cron = cron;
    }
}

這個(gè)是定時(shí)任務(wù)調(diào)度執(zhí)行器,采用的是注解的方式。首先要?jiǎng)討B(tài)配置,要設(shè)置為@EnableScheduling,這是確保能夠動(dòng)態(tài),然后實(shí)現(xiàn)SchedulingConfigurer,重寫(xiě)configureTasks方法,接下來(lái)就是這個(gè)的相關(guān)spring配置文件,要引入下面這個(gè)task,不然識(shí)別不了啊,配置文件就是這么簡(jiǎn)單

http://www.springframework.org/schema/task

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:task="http://www.springframework.org/schema/task"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/task
        http://www.springframework.org/schema/task/spring-task.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:component-scan base-package="com.seckill.quartz"/> 
    <task:annotation-driven /> 
</beans>

接下來(lái)就是寫(xiě)測(cè)試類(lèi),測(cè)試可不可行啊

package com.seckill.quartz;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException;
 
/**
 * Created by loup on 2017/11/11.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath*:/conf/spring-quartz.xml"})
public class QuartzTest {
 
    @Autowired
    private DynamicScheduledTask dynamicScheduledTask;
 
    @Test
    public void test1(){
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        dynamicScheduledTask.setCron("0/10 * * * * ?");
        try {
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

運(yùn)行測(cè)試類(lèi),查看結(jié)果,達(dá)到效果,親測(cè)可用

spring schedule 動(dòng)態(tài)配置執(zhí)行時(shí)間

之前saas平臺(tái)實(shí)現(xiàn)動(dòng)態(tài)修改定時(shí)任務(wù)的時(shí)間,都是通過(guò)xx-job這樣的框架來(lái)實(shí)現(xiàn),這樣我們可以單獨(dú)一個(gè)服務(wù)來(lái)管理我們整個(gè)saas平臺(tái)的定時(shí)任務(wù),但是最近給銀行做的一個(gè)小項(xiàng)目,需要本地化部署,所以我不想弄很多的服務(wù),并且他們并沒(méi)有要求修改以后即時(shí)生效,所以我直接采用了 spring schedule結(jié)合mysql動(dòng)態(tài)配置執(zhí)行時(shí)間。

之前我們用的schedule通過(guò)注解的方式,只能用靜態(tài)的corn表達(dá)式,如果想實(shí)現(xiàn)動(dòng)態(tài)的需要實(shí)現(xiàn)SchedulingConfigurer,并且通過(guò)注解@EnableScheduling。如下:

package com.zqf.marketing.task;  
import com.zqf.db.marketingrobot.sys.model.RobotSysSwitch;
import com.zqf.marketing.sys.service.SwitchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service; 
import java.util.Date;
 
/**
 * @author zhenghao
 * @description
 * @date 2019/1/22 21:50
 */
 
@Lazy(false)
@Service
@EnableScheduling
public class TestTaskService implements SchedulingConfigurer { 
    private static Logger log = LoggerFactory.getLogger(TestTaskService.class);
    @Autowired
    private SwitchService switchService;  
    private String SpringDynamicCronTask() {
        String cron = "0/5 * * * * ?";
        //從數(shù)據(jù)庫(kù)獲得配置的corn表達(dá)式
        RobotSysSwitch switchById = switchService.getSwitchById(5L);
        cron = switchById.getSwitchFlag();
        log.info(cron);
        return cron;
    } 
 
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
                // 任務(wù)邏輯
                log.info("task_task_tak");
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                String s = SpringDynamicCronTask();
                // 任務(wù)觸發(fā),可修改任務(wù)的執(zhí)行周期
                CronTrigger trigger = new CronTrigger(s);
                Date nextExec = trigger.nextExecutionTime(triggerContext);
                return nextExec;
            }
        });  
    }
}

看完了這篇文章,相信你對(duì)“如何使用spring-task定時(shí)任務(wù)動(dòng)態(tài)配置修改執(zhí)行時(shí)間”有了一定的了解,如果想了解更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI