Preface
Execution of timing tasks is a common requirement in modern application development. Whether it is performing batch jobs regularly, sending email notifications, or cleaning up useless data, timing tasks play an important role in many applications.
The Spring framework provides powerful tools for handling this requirement, where@Scheduled
and@Schedules
Annotations are like secret weapons in this field.
This blog will take you into the depth of these two annotations, explain how they work, and how to use them in Spring applications to manage various timing tasks.
Part 1: What is a timed task
A timing task is a mechanism for performing predetermined tasks or operations in an application. These tasks can be performed at a predetermined time, date, or periodic, and are usually used to perform some automated operations such as data backup, report generation, system maintenance, etc.
Timing tasks are very important in application development for the following reasons:
- Automated processing: Timing tasks allow developers to automatically perform repetitive or scheduled tasks without manual intervention. This can increase productivity, reduce the risk of human error, and save time and resources.
- Data processing: Timing tasks are often used for data processing, such as regularly obtaining data from external data sources, cleaning data, importing data into databases, etc. This ensures data consistency and timeliness.
- System maintenance: Timed tasks can be used to perform system maintenance tasks, such as cleaning of log files, reconstruction of database indexes, and monitoring of server performance. This helps ensure application stability and performance.
- Plan tasks: For tasks that need to be performed on schedule, such as sending regular reports or notifications, timing tasks are the ideal solution. This helps ensure that tasks are executed on time and are not missed.
- Resource Management: Timing tasks can help effectively manage system resources. For example, resource-intensive tasks can be started and stopped on demand to make the most of server resources without causing resource waste.
In software development, timing task schedulers or libraries provided by programming languages or frameworks are often used to create and manage timing tasks. These timing tasks are usually accompanied by code implementations to ensure the correct execution of tasks and can be monitored and logged when needed.
With good annotations, the code can be made easier to maintain and scale while helping other developers understand the purpose and functionality of the task.
Part 2: Detailed explanation of @Scheduled and @Schedules annotations
When it comes to timing task support in Spring framework, there are two main annotations, namely@Scheduled
and@Schedules
, They allow you to perform periodic tasks in your application. Here is a more detailed explanation:
@Scheduled annotation
@Scheduled
Annotation is used to mark a method as a timing task that will be executed according to the specified schedule. You can@Scheduled
Annotation methods to apply to Spring-managed beans.
Commonly used @Scheduled annotation properties
-
fixedRate
Attribute: Perform tasks according to fixed frequency.
@Scheduled(fixedRate = 5000) // Every other5Execute once in seconds
-
fixedDelay
Attribute: After the task is completed, wait for a fixed period of time before executing the next time.
@Scheduled(fixedDelay = 5000) // After the task is executed,wait5Execute the next time in seconds
-
initialDelay
Properties: The delay time before the first task is executed after the application is started.
@Scheduled(initialDelay = 3000, fixedRate = 5000) // Wait after startup3Second,Then every other5Second执行一次
-
cron
Properties: Use Cron expressions to define the execution time of a task, which can achieve highly flexible scheduling.
@Scheduled(cron = "0 0 2 * * ?") // Every morning2Click to execute
@Schedules annotation
@Schedules
Annotation is a container annotation that allows multiple specifications to be specified at the same time.@Scheduled
Annotation configuration. This is useful for timing tasks that define multiple different schedules.
You can apply multiple methods@Scheduled
Annotation, or use@Schedules
Encapsulate them in a container.
@Schedules({ @Scheduled(fixedRate = 5000), // Execute every 5 seconds @Scheduled(cron = "0 0 2 * * ?") // Perform at 2 am every day}) public void myScheduledMethods() { // Code for timing task execution}
These annotations allow you to easily create and manage timing tasks in your Spring application. You can choose the appropriate schedule and task scheduling strategy based on your needs. In this way, you can automate various tasks such as data cleaning, notification generation, periodic reporting, and more. At the same time, using appropriate comments and documentation can make the code more readable and maintainable.
Detailed explanation of cron expression
Cron expressions are a flexible and powerful way to define the execution time of a timed task. It usually consists of 6 or 7 fields, which represent seconds, minutes, hours, which day of the month, month, which day of the week, and optional year fields.
The syntax of a Cron expression is as follows:
┌───────────── Second (0 - 59) │ ┌───────────── minute (0 - 59) │ │ ┌───────────── Hour (0 - 23) │ │ │ ┌───────────── Which day of a month (1 - 31) │ │ │ │ ┌───────────── month (1 - 12 or JAN-DEC) │ │ │ │ │ ┌───────────── Which day of a week (0 - 6 or SUN-SAT, 7expressSUN) │ │ │ │ │ │ ┌───────────── years (Optional) │ │ │ │ │ │ │ │ │ │ │ │ │ │ * * * * * * *
Here is a detailed description of each field:
- Seconds (0 - 59): Indicates the number of seconds in one minute. For example, 0 means the task is executed at the beginning of each minute, and 30 means the task is executed at 30 seconds per minute.
- Minutes (0 - 59): Indicates the number of minutes in one hour. For example, 0 means the task is executed at the beginning of an hour, and 30 means the task is executed at the 30 minutes of an hour.
- Hours (0 - 23): Indicates the number of hours in a day. For example, 0 means the task is executed at midnight every day, and 12 means the task is executed at noon every day.
- Which day of the month (1 - 31): Indicates the specific date within one month. For example, 1 means the task is executed on the first day of each month, and 15 means the task is executed on the 15th of each month.
- Month (1 - 12 or JAN-DEC): Indicates the month within one year. You can use the number (1 - 12) or the abbreviated month name (JAN-DEC). For example, 1 or JAN means January, 12 or DEC means December.
- Which day of the week (0 - 6 or SUN-SAT, 7 means SUN): Indicates the specific date of the week. You can use the number (0 - 6, where 0 means Sunday) or the abbreviated name of the week (SUN-SAT). For example, 1 or MON means Monday, and 7 or SUN means Sunday.
- Year (optional): This field is optional and is used to specify the year the task is executed. Normally, you do not need to specify a year.
Here are some example Cron expressions:
*/5 * * * * ? Every other5Execute once in seconds 0 */1 * * * ? Every other1Execute once in minutes 0 0 5-15 * * ? every day5-15Point-to-point trigger 0 0/3 * * * ? Triggered every three minutes 0 0-5 14 * * ? 在every dayafternoon2Click to afternoon2:05During each period1Minute trigger 0 0/5 14 * * ? 在every dayafternoon2Click to afternoon2:55During each period5Minute trigger 0 0/5 14,18 * * ? 在every dayafternoon2Click to2:55Period and afternoon6Click to6:55During each period5Minute trigger 0 0/30 9-17 * * ? Every half hour from 9 to 5 working hours 0 0 10,14,16 * * ? every day上午10point,afternoon2point,4point 0 0 12 ? * WED Indicates every Wednesday at noon12point 0 0 17 ? * TUES,THUR,SAT Tuesday、Four、六afternoon五point 0 10,44 14 ? 3 WED each year三moon的星期三的afternoon2:10and2:44trigger 0 15 10 ? * MON-FRI Monday to Friday morning10:15trigger 0 0 23 L * ? Last day of each month23point执行一次 0 15 10 L * ? On the morning of the last day of each month10:15trigger 0 15 10 ? * 6L The last Friday morning of each month10:15trigger 0 15 10 * * ? 2005 2005Year的every day上午10:15trigger 0 15 10 ? * 6L 2002-2005 2002Year to2005Year的The last Friday morning of each month10:15trigger 0 15 10 ? * 6#3 Triggered on the third Friday of each month at 10:15 am 30 * * * * ? Every半Minute trigger任务 30 10 * * * ? Hourly10point30Secondtrigger任务 30 10 1 * * ? every day1point10point30Secondtrigger任务 30 10 1 20 * ? per month20Number1point10point30Secondtrigger任务 30 10 1 20 10 ? * each year10moon20Number1point10point30Secondtrigger任务 30 10 1 20 10 ? 2011 2011Year10moon20Number1point10point30Secondtrigger任务 30 10 1 ? 10 * 2011 2011Year10moonevery day1point10point30Secondtrigger任务 30 10 1 ? 10 SUN 2011 2011Year10moonEvery周日1point10point30Secondtrigger任务 15,30,45 * * * * ? Every15Second,30Second,45Second时trigger任务 15-45 * * * * ? 15arrive45Second内,EverySecond都trigger任务 15/5 * * * * ? Everypoint钟的Every15Second开始trigger,Every other5Secondtrigger一次 15-30/5 * * * * ? Everypoint钟的15Secondarrive30Second之间开始trigger,Every other5Secondtrigger一次 0 0/3 * * * ? Hourly第0point0Second开始,Triggered every three minutes 0 15 10 ? * MON-FRI 星期一arrive星期五的10point15point0Secondtrigger任务 0 15 10 L * ? Every个moon最后一天的10point15point0Secondtrigger任务 0 15 10 LW * ? Every个moon最后一个工作日的10point15point0Secondtrigger任务 0 15 10 ? * 5L Every个moon最后一个星期Four的10point15point0Secondtrigger任务 0 15 10 ? * 5#3 Every个moon第三周的星期Four的10point15point0Secondtrigger任务
Cron expressions are very flexible and can meet various complex scheduling needs. In Spring, you can use@Scheduled
The annotatedcron
Properties to configure Cron expressions to implement highly customized timing tasks.
Part 3: Advanced Usage
In the Spring framework, you can pass parameters in different ways the timed task method can be implemented, and exception handling and error handling strategies can be implemented. Additionally, you can enable asynchronous timing tasks for performance improvements. Let me explain these advanced usage in detail below:
1. Pass parameters to give the task method
You can@Scheduled
Annotation passes parameters to give task method. Here is an example:
@Service public class ScheduledTaskService { @Scheduled(fixedRate = 5000) public void taskWithParameters() { // Pass parameters in timing task method executeTask("Task with parameters", 42); } public void executeTask(String taskName, int value) { // Execute the task and use the passed parameters (taskName + " - Parameter value: " + value); } }
In this example,taskWithParameters
The method is a timed task, which usesexecuteTask
Methods to execute tasks and pass two parameters: task name and an integer value.
2. Exception handling and error handling strategies
In the timing task method, you can use the standard exception handling mechanism to handle exceptions. Spring provides a way to wrap the timing task method in onetry-catch
block to handle possible throw exceptions. You can also use Spring's@Scheduled
Annotated@ExceptionHandler
Properties to specify exception handling methods.
Here is an example showing how to handle exceptions in a timed task method:
@Service public class ScheduledTaskService { @Scheduled(fixedRate = 5000) public void taskWithException() { try { // Code that may throw exceptions throw new RuntimeException("An error occurred"); } catch (Exception e) { // Exception handling logic ("Exception caught: " + ()); } } }
3. Enable asynchronous timing tasks
To enable asynchronous timing tasks, you can use them on the timing task method@Async
Annotation and enable asynchronous support in Spring configuration. Here is an example:
First, make sure you enable asynchronous support in your Spring configuration:
<task:annotation-driven executor="taskExecutor" /> <task:executor pool-size="5" />
Then, use it on the timing task method@Async
annotation:
@Service public class ScheduledTaskService { @Async @Scheduled(fixedRate = 5000) public void asyncTask() { // Asynchronous execution of tasks ("Async task is running..."); } }
This will makeasyncTask
Methods are executed asynchronously in a separate thread without blocking the main thread. This is useful for performing time-consuming timing tasks to improve application performance and responsiveness.
Note that enabling asynchronous timing tasks requires proper configuration and thread pool management to ensure the correct execution of tasks and the rational use of resources.
Part 4: Best Practices
Here are best practices for writing maintainable and efficient timing tasks:
Clear naming and comments:
- Use clear, descriptive naming for timing task methods and classes so that other developers can easily understand their purpose.
- Provide detailed comments explaining the purposes, parameters and special considerations of each timing task.
Separate business logic:
- Keep the timing task method concise and only contains logic related to the timing task itself.
- Move the actual business logic of the task to a separate service or component to improve the testability and maintainability of the code.
Error handling:
- Implement appropriate error handling strategies to handle possible exceptions.
- use
try-catch
Blocks to catch exceptions, ensuring that the entire application is not interrupted due to exceptions.
Usage parameters:
- If the timing tasks require parameters, use method parameters to pass them instead of hard-coded in the method. This makes timing tasks more versatile and easy to maintain.
Scheduling strategy for timing tasks:
- Carefully select scheduled strategies for timing tasks (e.g.
fixedRate
orcron
) to ensure that the task is performed as required. - Consider the concurrency of timing tasks to avoid multiple instances performing the same task at the same time.
Asynchronous tasks:
- use
@Async
Annotation marks time-consuming tasks asynchronous - To improve application performance and responsiveness
Monitoring and logging:
- Implement proper logging to allow troubleshooting in the event of a problem.
- Use monitoring tools to track the execution of scheduled tasks and whether the tasks are executed as planned.
test:
- Write unit tests to verify the logic and correctness of timing tasks.
- Use mock or forged objects to simulate dependencies of timed tasks to make unit testing easier.
External configuration of timing task parameters:
- Avoid hard-coded parameters of timing tasks.
- Use external configuration files or properties to modify the parameters of the timing task without recompiling the code.
Availability and stability of timing tasks:
- Consider application restarts and failure recovery to ensure availability and stability of timing tasks.
- Use a database or other persistent storage to record the execution status of a task so that it can be restored correctly after the application crashes.
By following these best practices, you can write maintainable, efficient, and stable timing tasks that ensure they are executed on schedule in the application and meet business needs.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.