例如:系统启动 读取时间 cron : 0 0 3 * * ? ,通过执行后台方法 可以动态配置 cron 时间格式,并且清楚掉原本执行任务,执行新的设置定时任务时间
1、根据 threadpooltaskscheduler 、scheduledfuture 类 动态修改定时任务(threadpooltaskscheduler 这个类 不能使用@autowired ,直接定义成员变量 )
private threadpooltaskscheduler threadpooltaskscheduler;private scheduledfuture<?> future;
2、动态修改 scheduled 后台方法逻辑(object 是 runnable 实现类 需要执行的定时逻辑,放到run 线程方法内)
threadpooltaskscheduler = new threadpooltaskscheduler();threadpooltaskscheduler.initialize();if(future!=null){ future.cancel(true);}future=threadpooltaskscheduler.schedule(object,new crontrigger("需要cron时间格式字符串") );
以上逻辑 ----------------------- 就可以实现 动态 scheduled 配置
以下逻辑 ----------------------- 配置项目启动 自动读取 db cron 设置定时
1、@order 并实现 commandlinerunner 类 重写方法 run
@override public void run(string... args) throws exception { logger.info("系统启动 默认设置对账任务 时间"); //获取目前db 设置的对账时间 getbilltimeresp time = systemconfigservice.gettime(); //获取cron时间格式字符串 string timecron = billtimecronformat(time.getbilltime()); logger.info("时间为:"+timecron); //scheduler 设置每天执行。。。 threadpooltaskscheduler = new threadpooltaskscheduler(); threadpooltaskscheduler.initialize(); future=threadpooltaskscheduler.schedule(object,new crontrigger("db cron时间格式字符串")); }
springboot项目@scheduled读取动态参数1、基于@scheduled可配置开发application.propertites: read.timer.parmas=0 0/1 * * * *
定时类:
@componentpublic 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@enableschedulingpublic 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 * * * * *"
以上就是springboot怎么动态修改scheduled的详细内容。
