SpringBoot項目中使用@Scheduled讀取動態參數

使用@Scheduled讀取動態參數

1、基於@Scheduled可配置開發

application.propertites: 
read.timer.parmas=0 0/1 * * * *

定時類:

@Component
public class ScheduledService {
Logger logger= LoggerFactory.getLogger(ScheduledService.class);
    @Scheduled(cron = "${read.timer.parmas}")
    public void readConfigTable(){
        logger.info("*****.read.timer.parmas");
    }
}

啟動類:

@SpringBootApplication
@EnableScheduling  //必須
public class DataApplication {
  public static void main(String[] args) {
        SpringApplication.run(DataApplication.class,args);
    }
}

2、基於代碼實現

(1)核心代碼

@Component
@EnableScheduling
public class TestScheduledParams implements SchedulingConfigurer{
    Logger logger= LoggerFactory.getLogger(TestScheduledParams.class);
 
    public static  String DEFAULT_CORN="0/3 * * * * *";
    //##動態傳參要給默認值。
    public static String corn=DEFAULT_CORN;
 
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
     
        taskRegistrar.addTriggerTask(new Runnable() {
            @Override
            public void run() {
               // logger.info("定時任務邏輯");
            }
        }, new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                //任務觸發,可修改任務的執行周期
                CronTrigger cronTrigger = new CronTrigger(corn);
 
                Date date = cronTrigger.nextExecutionTime(triggerContext);
                return date;
            }
        });
    }
}

(2)其他類或方法動態傳參賦值

TestScheduledParams.corn="0/20 * * * * *"

spring boot Scheduled動態配置

package cn.com.suntree.cmp.service;
import cn.com.suntree.cmp.utils.CommonUtil;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import java.util.Date;
@Component
@Log4j2
public class MyDynamicTask implements SchedulingConfigurer {//實現SchedulingConfigurer 接口
    @Autowired
    CommonUtil commonUtil;
    @Autowired
    TaskService taskService;
    private static String cron;
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {//重寫該方法
        scheduledTaskRegistrar.addTriggerTask(doTask(), getTrigger());
    }
    private Runnable doTask() {
        return new Runnable() {
            @Override
            public void run() {
                log.info("-------------------------------執行"+cron);
                taskService.monDay();//真正需要運行的邏輯代碼
            }
        };
    }
    private Trigger getTrigger() {
        return new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // 觸發器
                CronTrigger trigger = new CronTrigger(getCron());
                return trigger.nextExecutionTime(triggerContext);
            }
        };
    }
    public String getCron() {
        Jedis jedis = commonUtil.getJedis();
        String newCron =  jedis.get("cron");//可以改成配置到數據庫中
        if (StringUtils.isEmpty(newCron)) {
            jedis.set("cron","0 30 0 ? * Mon");
            return "0 30 0 ? * Mon";
        }
        if (!newCron.equals(cron)) {
            log.info(new StringBuffer("Cron has been changed to:'").append(newCron).append("'. Old cron was:'").append(cron).append("'").toString());
            cron = newCron;
        }
        return cron;
    }
}

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: