0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

如何在SpringBoot项目中实现动态定时任务

我快闭嘴 来源:CSDN技术社区 作者:CSDN技术社区 2022-09-30 11:16 次阅读

之前写过文章记录怎么在SpringBoot项目中简单使用定时任务,不过由于要借助cron表达式且都提前定义好放在配置文件里,不能在项目运行中动态修改任务执行时间,实在不太灵活。

经过网上搜索学习后,特此记录如何在SpringBoot项目中实现动态定时任务。

因为只是一个demo,所以只引入了需要的依赖:



org.springframework.boot
spring-boot-starter-web



org.springframework.boot
spring-boot-starter-log4j2
true


 

org.springframework.boot
spring-boot-starter-validation



org.projectlombok
lombok
true


启动类:

packagecom.wl.demo;

importorg.springframework.boot.SpringApplication;
importorg.springframework.boot.autoconfigure.SpringBootApplication;
importorg.springframework.scheduling.annotation.EnableScheduling;

/**
*@authorwl
*/
@EnableScheduling
@SpringBootApplication
publicclassDemoApplication{

publicstaticvoidmain(String[]args){
SpringApplication.run(DemoApplication.class,args);
System.out.println("(*^▽^*)启动成功!!!(〃'▽'〃)");
}
}

配置文件application.yml,只定义了服务端口

server:
port:8089

定时任务执行时间配置文件:task-config.ini:

printTime.cron=0/10****?

定时任务执行类:

packagecom.wl.demo.task;

importlombok.Data;
importlombok.extern.slf4j.Slf4j;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.context.annotation.PropertySource;
importorg.springframework.scheduling.Trigger;
importorg.springframework.scheduling.TriggerContext;
importorg.springframework.scheduling.annotation.SchedulingConfigurer;
importorg.springframework.scheduling.config.ScheduledTaskRegistrar;
importorg.springframework.scheduling.support.CronTrigger;
importorg.springframework.stereotype.Component;

importjava.time.LocalDateTime;
importjava.util.Date;

/**
*定时任务
*@authorwl
*/
@Data
@Slf4j
@Component
@PropertySource("classpath:/task-config.ini")
publicclassScheduleTaskimplementsSchedulingConfigurer{

@Value("${printTime.cron}")
privateStringcron;

@Override
publicvoidconfigureTasks(ScheduledTaskRegistrartaskRegistrar){
//动态使用cron表达式设置循环间隔
taskRegistrar.addTriggerTask(newRunnable(){
@Override
publicvoidrun(){
log.info("Current time:{}",LocalDateTime.now());
}
},newTrigger(){
@Override
publicDatenextExecutionTime(TriggerContexttriggerContext){
//使用CronTrigger触发器,可动态修改cron表达式来操作循环规则
CronTriggercronTrigger=newCronTrigger(cron);
DatenextExecutionTime=cronTrigger.nextExecutionTime(triggerContext);
returnnextExecutionTime;
}
});
}
}

编写一个接口,使得可以通过调用接口动态修改该定时任务的执行时间:

packagecom.wl.demo.controller;

importcom.wl.demo.task.ScheduleTask;
importlombok.extern.slf4j.Slf4j;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;

/**
*@authorwl
*/
@Slf4j
@RestController
@RequestMapping("/test")
publicclassTestController{

privatefinalScheduleTaskscheduleTask;

@Autowired
publicTestController(ScheduleTaskscheduleTask){
this.scheduleTask=scheduleTask;
}

@GetMapping("/updateCron")
publicStringupdateCron(Stringcron){
log.info("newcron:{}",cron);
scheduleTask.setCron(cron);
return"ok";
}
}

启动项目,可以看到任务每10秒执行一次:

cbf90050-4065-11ed-b1c7-dac502259ad0.png

访问接口,传入请求参数cron表达式,将定时任务修改为15秒执行一次:

cc1f6740-4065-11ed-b1c7-dac502259ad0.png

可以看到任务变成了15秒执行一次

cc4bd6e0-4065-11ed-b1c7-dac502259ad0.png

除了上面的借助cron表达式的方法,还有另一种触发器,区别于CronTrigger触发器,该触发器可随意设置循环间隔时间,不像cron表达式只能定义小于等于间隔59秒。

packagecom.wl.demo.task;

importlombok.Data;
importlombok.extern.slf4j.Slf4j;
importorg.springframework.beans.factory.annotation.Value;
importorg.springframework.context.annotation.PropertySource;
importorg.springframework.scheduling.Trigger;
importorg.springframework.scheduling.TriggerContext;
importorg.springframework.scheduling.annotation.SchedulingConfigurer;
importorg.springframework.scheduling.config.ScheduledTaskRegistrar;
importorg.springframework.scheduling.support.CronTrigger;
importorg.springframework.scheduling.support.PeriodicTrigger;
importorg.springframework.stereotype.Component;

importjava.time.LocalDateTime;
importjava.util.Date;

/**
*定时任务
*@authorwl
*/
@Data
@Slf4j
@Component
@PropertySource("classpath:/task-config.ini")
publicclassScheduleTaskimplementsSchedulingConfigurer{

@Value("${printTime.cron}")
privateStringcron;

privateLongtimer=10000L;

@Override
publicvoidconfigureTasks(ScheduledTaskRegistrartaskRegistrar){
//动态使用cron表达式设置循环间隔
taskRegistrar.addTriggerTask(newRunnable(){
@Override
publicvoidrun(){
log.info("Current time:{}",LocalDateTime.now());
}
},newTrigger(){
@Override
publicDatenextExecutionTime(TriggerContexttriggerContext){
//使用CronTrigger触发器,可动态修改cron表达式来操作循环规则
//CronTriggercronTrigger=newCronTrigger(cron);
//DatenextExecutionTime=cronTrigger.nextExecutionTime(triggerContext);

//使用不同的触发器,为设置循环时间的关键,区别于CronTrigger触发器,该触发器可随意设置循环间隔时间,单位为毫秒
PeriodicTriggerperiodicTrigger=newPeriodicTrigger(timer);
DatenextExecutionTime=periodicTrigger.nextExecutionTime(triggerContext);
returnnextExecutionTime;
}
});
}
}

增加一个修改时间的接口:

packagecom.wl.demo.controller;

importcom.wl.demo.task.ScheduleTask;
importlombok.extern.slf4j.Slf4j;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.web.bind.annotation.GetMapping;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RestController;

/**
*@authorwl
*/
@Slf4j
@RestController
@RequestMapping("/test")
publicclassTestController{

privatefinalScheduleTaskscheduleTask;

@Autowired
publicTestController(ScheduleTaskscheduleTask){
this.scheduleTask=scheduleTask;
}

@GetMapping("/updateCron")
publicStringupdateCron(Stringcron){
log.info("newcron:{}",cron);
scheduleTask.setCron(cron);
return"ok";
}

@GetMapping("/updateTimer")
publicStringupdateTimer(Longtimer){
log.info("newtimer:{}",timer);
scheduleTask.setTimer(timer);
return"ok";
}
}

测试结果:

cc85a49c-4065-11ed-b1c7-dac502259ad0.png

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

项目地址:https://gitee.com/zhijiantianya/ruoyi-vue-pro

视频教程:https://doc.iocoder.cn/video/

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

项目地址:https://gitee.com/zhijiantianya/yudao-cloud

视频教程:https://doc.iocoder.cn/video/

审核编辑:汤梓红
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 接口
    +关注

    关注

    33

    文章

    7574

    浏览量

    148207
  • spring
    +关注

    关注

    0

    文章

    332

    浏览量

    14143
  • SpringBoot
    +关注

    关注

    0

    文章

    172

    浏览量

    99

原文标题:SpringBoot 设置动态定时任务,千万别再写死了~

文章出处:【微信号:芋道源码,微信公众号:芋道源码】欢迎添加关注!文章转载请注明出处。

收藏 人收藏

    评论

    相关推荐

    关于stm32系统定时任务的问题

    在用stm32做一个飞控程序时。需要用到上面这种系统循环定时任务,有一个问题:在System_Task_Loop函数里面,有1ms 、2ms、5ms的循环任务,但是他的这些定时是怎么得到的?是随便
    发表于 10-10 23:43

    Linux系统定时任务Crond

    会定期(默认每分钟检查一次)检查系统中是否有要执行的任务工作,如果有,便会根据其预先设定的定时任务规则自动执行该定时任务工作,这个crond定时任务服务就相当于我们平时早起使用的闹钟一
    发表于 07-05 06:22

    linux的循环定时任务

    linux循环定时任务
    发表于 05-20 14:59

    定时任务的发展史是怎么样的

    定时任务是互联网行业里最常用的服务之一,本文给大家介绍定时任务在我司的发展历程。 linux系统中一般使用crontab命令来实现,在Java世界里,使用最广泛的就是quartz
    发表于 07-18 17:38 0次下载
    <b class='flag-5'>定时任务</b>的发展史是怎么样的

    SpringBoot如何实现动态增删启停定时任务

    在spring boot项目中,可以通过 @EnableScheduling 注解和@Scheduled注解实现定时任务,也可以通过SchedulingConfigurer接口来实现
    的头像 发表于 09-24 09:49 2555次阅读
    <b class='flag-5'>SpringBoot</b>如何<b class='flag-5'>实现</b><b class='flag-5'>动态</b>增删启停<b class='flag-5'>定时任务</b>

    Python定时任务实现方式

    在日常工作中,我们常常会用到需要周期性执行的任务,一种方式是采用 Linux 系统自带的 crond 结合命令行实现。另外一种方式是直接使用Python。接下来整理的是常见的Python定时任务
    的头像 发表于 10-08 15:20 3197次阅读

    解析Golang定时任务库gron设计和原理

    正巧,最近看到了 gron 这个开源项目,它是用 Golang 实现一个并发安全的定时任务库。实现非常简单精巧,代码量也不多。今天我们就来一起结合源码看一下,怎样基于 Golang 的
    的头像 发表于 12-15 13:57 913次阅读

    求一种SpringBoot定时任务动态管理通用解决方案

    SpringBoot定时任务的加强工具,实现SpringBoot原生的定时任务进行动态管理,
    的头像 发表于 02-03 09:49 520次阅读

    SpringBoot如何实现定时任务(下)

    SpringBoot创建定时任务的方式很简单,主要有两种方式:一、基于注解的方式(@Scheduled)二、数据库动态配置。实际开发中,第一种需要在代码中写死表达式,如果修改起来,又得重启会显得很麻烦;所以我们往往会采取第二种方
    的头像 发表于 04-07 14:51 1012次阅读
    <b class='flag-5'>SpringBoot</b>如何<b class='flag-5'>实现</b><b class='flag-5'>定时任务</b>(下)

    SpringBoot如何实现定时任务(上)

    SpringBoot创建定时任务的方式很简单,主要有两种方式:一、基于注解的方式(@Scheduled)二、数据库动态配置。实际开发中,第一种需要在代码中写死表达式,如果修改起来,又得重启会显得很麻烦;所以我们往往会采取第二种方
    的头像 发表于 04-07 14:51 998次阅读
    <b class='flag-5'>SpringBoot</b>如何<b class='flag-5'>实现</b><b class='flag-5'>定时任务</b>(上)

    Spring Boot中整合两种定时任务的方法

    在 Spring + SpringMVC 环境中,一般来说,要实现定时任务,我们有两中方案,一种是使用 Spring 自带的定时任务处理器 @Scheduled 注解,另一种就是使用第三方
    的头像 发表于 04-07 14:55 1215次阅读
    Spring Boot中整合两种<b class='flag-5'>定时任务</b>的方法

    在Spring Boot中如何使用定时任务

    本文介绍在 Spring Boot 中如何使用定时任务,使用非常简单,就不做过多说明了。
    的头像 发表于 04-12 10:56 760次阅读

    如何动态添加修改删除定时任务

    如何动态添加修改删除定时任务?那么我们一起看看具体怎么实现,先看下本节大纲: (1)思路说明; (2)代码解析; (3)修改定时任务执行周期特别说明;
    的头像 发表于 04-12 11:06 853次阅读

    python定时任务实践

    由于程序需求,监测配置变化需要设置定时任务,每分钟执行一次,对任务持久化要求不高,不需要时可以关闭定时任务
    的头像 发表于 05-20 17:53 756次阅读
    python<b class='flag-5'>定时任务</b>实践

    定时器如何实现定时任务

    1.1、单次定时任务实现 boost 的asio库里有几个定时器,老的有 deadline_timer , 还有三个可配合 C++11 的 chrono
    的头像 发表于 11-09 17:20 312次阅读