When it comes to scheduled tasks, we should think of @Scheduled, Quartz and XXL-JOB, but some single services or small projects may directly use @Scheduled to implement asynchronous tasks for convenience and speed. Therefore, the theme requirements of this article are extended.
When using @Scheduled in a project, how can we execute the specified asynchronous task in advance when the project starts?
1. @Scheduled Detailed Explanation
The @Scheduled annotation supports multiple parameters for flexible control of task execution time
cron: Cron expression, which can accurately control seconds, minutes, hours, days, months, weeks, etc.
zone: Receives a time zone, such as the time zone Asia/Shanghai that we generally use. We usually leave this field blank.
fixedDelay: how long after the last execution to wait before executing again. For example, @Scheduled(fixedDelay = 5000)
fixedDelayString: Same as fixedDelay, but in string format. The only difference is that it supports placeholders, such as @Scheduled(fixedDelayString = "5000")
fixedRate: how long after the last execution time to execute again, such as @Scheduled(fixedRate = 5000)
fixedRateString: Same as fixedRate, but in string format. The only difference is that it supports placeholders.
initialDelay: How long to delay the first time before executing. For example, the first time it is executed after a delay of 1 second, and then it is executed every 5 seconds according to the fixedRate rule @Scheduled(initialDelay=1000, fixedRate=5000)
initialDelayString: Same as initialDelayString, but in string format. The only difference is that it supports placeholders.
Note: Remember to add @EnableScheduling to the startup class so that the scheduled task will be executed. Of course, this does not affect the logical test of this article
3. Test Results
After the service is started, check the print information