Implementing Java Scheduled Tasks with Spring: Configuration Files, Annotations, and Cron Expressions
This article explains how to create Java scheduled tasks using Spring's built‑in task scheduler, covering XML configuration, annotation‑based setup, dynamic code addition, and detailed usage of cron expressions for precise timing control.
In recent projects a reminder‑email feature is needed, which can be realized by a scheduled scanning task. This article introduces how to implement such a function in Java.
Java provides several ways to implement scheduled tasks:
JDK built‑in: Timer and ScheduledExecutorService (JDK 1.5+).
Quartz: a simple yet powerful job‑scheduling framework.
Spring 3.0+ task scheduling: a lightweight alternative to Quartz, easier to use.
The focus here is on the third method, using Spring's TaskScheduler and its implementations.
1. Spring XML Configuration
Configuration can be defined in the Spring XML file (see the accompanying screenshots).
2. Annotation‑Based Configuration
Spring also supports annotations such as @Scheduled to define tasks directly in Java classes (see the screenshots).
3. Dynamic Code Addition
Tasks can also be added programmatically at runtime (see the screenshots).
Cron Expression Usage
Cron expressions are strings with 5–7 fields separated by spaces, defining seconds, minutes, hours, day‑of‑month, month, day‑of‑week, and optional year. The article lists the allowed characters for each field and explains common symbols such as * (any value), ? (no specific value), - (range), and # (nth weekday of the month).
Example fields:
Seconds: ", - * /" (0‑59)
Minutes: ", - * /" (0‑59)
Hours: ", - * /" (0‑23)
DayofMonth: ", - * / ? L W C" (0‑31)
Month: ", - * /" (1‑12 or JAN‑DEC)
DayofWeek: ", - * / ? L C #" (1‑7 or SUN‑SAT)
Year: ", - * /" (1970‑2099)
Summary
The article presents simple ways to implement Java scheduled tasks, primarily using Spring’s built‑in scheduler, and briefly mentions other methods such as Quartz and JDK timers. It also points to further resources for more advanced scenarios like dynamic task addition and Quartz clustering.
References
1) https://blog.csdn.net/kegumingxin2626/article/details/72854823
2) http://www.jb51.net/article/110541.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
360 Quality & Efficiency
360 Quality & Efficiency focuses on seamlessly integrating quality and efficiency in R&D, sharing 360’s internal best practices with industry peers to foster collaboration among Chinese enterprises and drive greater efficiency value.
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.
