I. Scheduled Tasks
Starting with Spring3.1, the implementation of the scheduled task in spring becomes unusually simple. The first step is to turn on support for the scheduled task by configuring the class annotation @enablescheduling, and then annotate @scheduled on the method that executes the scheduled task, declaring that this is a scheduled task.
Spring supports many types of scheduled tasks through @scheduled, including Cron, Fixdelay, fixrate, and more.
Example:
1. Task plan Execution class
PackageCom.ecworking.schedule;Importorg.springframework.scheduling.annotation.Scheduled;ImportOrg.springframework.stereotype.Service;ImportJava.text.SimpleDateFormat;Importjava.util.Date; @Service Public classSchduledtaskservice {Private Static FinalSimpleDateFormat DateFormat =NewSimpleDateFormat ("HH:mm:ss"); @Scheduled (Fixedrate= 5000)//declaring this method through @scheduled is a scheduled task that uses the Fixedrate property to execute at regular intervals Public voidReportcurrenttime () {System.out.println ("Execute once every five seconds:" + Dateformat.format (NewDate ())); } @Scheduled (Cron= "0 30 11?" * *")//use the Cron property to perform scheduled tasks at a specified time, where 11.30 executes; Cron is a timed task under Unix and Unix-like systems Public voidfixtimeexecution () {System.out.println ("Execute at specified time:" + Dateformat.format (NewDate ())); }}
2. Configure the class.
Package Com.ecworking.schedule; Import Org.springframework.context.annotation.ComponentScan; Import org.springframework.context.annotation.Configuration; Import org.springframework.scheduling.annotation.EnableScheduling, @Configuration @componentscan (" Com.ecworking.schedule "// open support for scheduled tasks via @enablescheduling Publicclass schduledtaskconfig {}
3. Run.
Package Com.ecworking.schedule; Import Org.springframework.context.annotation.AnnotationConfigApplicationContext; Public class Main { publicstaticvoid main (string[] args) { new Annotationconfigapplicationcontext (schduledtaskconfig. Class);} }
Operation Result:
Spring Boot Combat Notes (vii)--Spring Advanced topics (Scheduled Tasks)