This is a community that may be useful to you
One-to-one communication/interview brochure/resume optimization/job search questions, welcome to join the “Yudao Rapid Development Platform” Knowledge Planet. The following is some information provided by Planet:
“Project Practice (Video)”: Learn from books, “practice” from past events
“Internet High Frequency Interview Questions”: Studying with your resume, spring blossoms
“Architecture x System Design”: Overcoming difficulties and mastering high-frequency interview scenario questions
“Advancing Java Learning Guide”: systematic learning, the mainstream technology stack of the Internet
“Must-read Java Source Code Column”: Know what it is and why it is so
This is an open source project that may be useful to you
Domestic Star is a 100,000+ open source project. The front-end includes management backend + WeChat applet, and the back-end supports monomer and microservice architecture.
Functions cover RBAC permissions, SaaS multi-tenancy, data permissions, mall, payment, workflow, large-screen reports, WeChat public account, etc.:
Boot address: https://gitee.com/zhijiantianya/ruoyi-vue-pro
Cloud address: https://gitee.com/zhijiantianya/yudao-cloud
Video tutorial: https://doc.iocoder.cn
Source: blog.csdn.net/wl_Honest/
article/details/123654621
I have written an article before to record how to simply use scheduled tasks in SpringBoot projects. However, since it requires the use of cron expressions and is defined in advance and placed in the configuration file, the task execution time cannot be dynamically modified while the project is running, which is not very flexible.
After searching and learning on the Internet, I hereby record how to implement dynamic scheduled tasks in the SpringBoot project.
Backend management system + user applet implemented based on Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element, supporting RBAC dynamic permissions, multi-tenancy, data permissions, workflow, three-party login, payment, SMS, mall and other functions
Project address: https://github.com/YunaiV/yudao-cloud
Video tutorial: https://doc.iocoder.cn/video/
Because it is just a demo, only the required dependencies are introduced:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> <optional>true</optional> </dependency> <!-- After spring boot version 2.3, if you need to use verification, you need to manually import the validation package --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> </dependencies>
Startup class:
package com.wl.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; /** * @author wl */ @EnableScheduling @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); System.out.println("(*^▽^*)Start successfully!!!(〃'▽'〃)"); } }
The configuration file application.yml only defines the service port:
server: port: 8089
Scheduled task execution time configuration file: task-config.ini:
printTime.cron=0/10 * * * * ?
Scheduled task execution class:
package com.wl.demo.task; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; 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 java.time.LocalDateTime; import java.util.Date; /** * Scheduled tasks * @author wl */ @Data @Slf4j @Component @PropertySource("classpath:/task-config.ini") public class ScheduleTask implements SchedulingConfigurer { @Value("${printTime.cron}") private String cron; @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { //Dynamicly use cron expression to set loop interval taskRegistrar.addTriggerTask(new Runnable() { @Override public void run() { log.info("Current time: {}", LocalDateTime.now()); } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { // Use CronTrigger trigger to dynamically modify cron expressions to operate loop rules CronTrigger cronTrigger = new CronTrigger(cron); Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext); return nextExecutionTime; } }); } }
Write an interface so that the execution time of the scheduled task can be dynamically modified by calling the interface:
package com.wl.demo.controller; import com.wl.demo.task.ScheduleTask; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author wl */ @Slf4j @RestController @RequestMapping("/test") public class TestController { private final ScheduleTask scheduleTask; @Autowired public TestController(ScheduleTask scheduleTask) { this.scheduleTask = scheduleTask; } @GetMapping("/updateCron") public String updateCron(String cron) { log.info("new cron :{}", cron); scheduleTask.setCron(cron); return "ok"; } }
Start the project and you can see that the task is executed every 10 seconds:
Access the interface, pass in the request parameter cron expression, and modify the scheduled task to be executed every 15 seconds:
You can see that the task becomes executed every 15 seconds.
In addition to the above method using cron expressions, there is another trigger, which is different from the CronTrigger trigger. This trigger can set the cycle interval time arbitrarily, unlike the cron expression which can only define an interval less than or equal to 59 seconds.
package com.wl.demo.task; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.PropertySource; 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.scheduling.support.PeriodicTrigger; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.util.Date; /** * Scheduled tasks * @author wl */ @Data @Slf4j @Component @PropertySource("classpath:/task-config.ini") public class ScheduleTask implements SchedulingConfigurer { @Value("${printTime.cron}") private String cron; private Long timer = 10000L; @Override public void configureTasks(ScheduledTaskRegistrar taskRegistrar) { //Dynamicly use cron expression to set loop interval taskRegistrar.addTriggerTask(new Runnable() { @Override public void run() { log.info("Current time: {}", LocalDateTime.now()); } }, new Trigger() { @Override public Date nextExecutionTime(TriggerContext triggerContext) { // Use CronTrigger trigger to dynamically modify cron expressions to operate loop rules // CronTrigger cronTrigger = new CronTrigger(cron); // Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext); // Using different triggers is the key to setting the cycle time. Different from the CronTrigger trigger, this trigger can set the cycle interval time at will, in milliseconds. PeriodicTrigger periodicTrigger = new PeriodicTrigger(timer); Date nextExecutionTime = periodicTrigger.nextExecutionTime(triggerContext); return nextExecutionTime; } }); } }
Add an interface to modify time:
package com.wl.demo.controller; import com.wl.demo.task.ScheduleTask; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author wl */ @Slf4j @RestController @RequestMapping("/test") public class TestController { private final ScheduleTask scheduleTask; @Autowired public TestController(ScheduleTask scheduleTask) { this.scheduleTask = scheduleTask; } @GetMapping("/updateCron") public String updateCron(String cron) { log.info("new cron :{}", cron); scheduleTask.setCron(cron); return "ok"; } @GetMapping("/updateTimer") public String updateTimer(Long timer) { log.info("new timer :{}", timer); scheduleTask.setTimer(timer); return "ok"; } }
Test Results:
Welcome to join my knowledge planet and comprehensively improve your technical capabilities.
To join, “Long press” or “Scan” the QR code below:
Planet’s content includes: project practice, interviews and recruitment, source code analysis, and learning routes.
If the article is helpful, please read it and forward it. Thank you for your support (*^__^*)
The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138933 people are learning the system