Implementing Dynamic Scheduled Tasks in Spring Boot
This tutorial demonstrates how to create Spring Boot scheduled tasks whose execution intervals can be changed at runtime using both CronTrigger and PeriodicTrigger, providing REST endpoints to update the cron expression or timer value dynamically.
Previously a static scheduled task using cron expressions was described, but it required predefined configuration and could not be changed at runtime.
This article shows how to implement dynamic scheduled tasks in a Spring Boot project.
First, the required Maven dependencies are added (spring-boot-starter-web, spring-boot-starter-log4j2, spring-boot-starter-validation, lombok).
The main application class is annotated with @EnableScheduling and starts the Spring Boot application.
The server port is configured in application.yml , and the cron expression is stored in task-config.ini (e.g., printTime.cron=0/10 * * * * ? ).
A task class implements SchedulingConfigurer , reads the cron value with @Value("${printTime.cron}") , and registers a trigger task that uses a CronTrigger to determine the next execution time, allowing the cron expression to be changed at runtime.
A REST controller provides an endpoint /test/updateCron that receives a new cron string, updates the task’s cron field, and returns “ok”. After restarting the application, the task runs according to the new schedule (e.g., every 15 seconds).
For scenarios where a fixed‑interval trigger is preferred, the article replaces CronTrigger with PeriodicTrigger , which accepts a millisecond interval ( timer ) and adds another endpoint /test/updateTimer to modify this interval dynamically.
Running the application and invoking the endpoints demonstrates that the scheduled task can be switched between cron‑based and period‑based execution without restarting the service.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.