Scheduled task (scheduling tasks)
Creating a timed task in Springboot is simple and takes only 2 steps:
- 1. Add @enablescheduling annotations at the entrance of the program.
- 2. Add @scheduled annotations to the timing method.
1, springboot By default has helped us achieve a scheduled task, only need to add the corresponding annotations can be implementedspring-boot-starter2. Startup class Enable timing
Add annotations to the main class of spring boot @EnableScheduling to enable configuration of timed tasks
@SpringBootApplication @enablediscoveryclient@enablescheduling Public class memberapplication { publicstaticvoid main (string[] args) { Springapplication.run (memberapplication. class , args);} }
3. Create a timed Task implementation class
Create a timed task that prints the current time in the console every 5s.
@Component Public classScheduledtasks {Private Static FinalLogger log = Loggerfactory.getlogger (scheduledtasks.class); Private Static FinalSimpleDateFormat DateFormat =NewSimpleDateFormat ("HH:mm:ss"); @Scheduled (Fixedrate= 5000) Public voidReportcurrenttime () {Log.info ("The time is now {}", Dateformat.format (NewDate ())); }}4. Parameter description
@Scheduled Explanation
By adding @scheduled annotations to the method, it shows that the method is a dispatch task.
@ScheduledParameters can accept two timing settings, one that we commonly use cron="*/6 * * * * ?" , one of which is fixedRate = 6000 that both represent the printing of content every six seconds
@Scheduled (fixedrate =@scheduled): 5 Seconds after the last execution point (InitialDelay=1000, fixedrate=5000 ): Executes after the first delay of 1 seconds, followed by fixedrate rules every 5 seconds (cron= "*/5 * * * * *"): Define rules by cron expressions
Reference: Scheduling Tasks
13. Springboot Integrated timing task (scheduling tasks)