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 the @scheduled declaration on the method to perform the scheduled task. This is a scheduled task.
Spring supports many types of scheduled tasks through @scheduled, including Cron, Fixdelay, and Fixratedeng.
Example
1>. Scheduling Task Execution Classes
PackageCom.wisely.highlight_spring4.ch3.taskscheduler;ImportJava.text.SimpleDateFormat;Importjava.util.Date;Importorg.springframework.scheduling.annotation.Scheduled;ImportOrg.springframework.stereotype.Service; @Service Public classScheduledtaskservice {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 ("Executes once every 5 seconds" + Dateformat.format (NewDate ())); } @Scheduled (Cron= "0 28 11?" * *" )//use the Cron property to execute at a specified time, which in this case is 11:28 execution; Cron is a scheduled task under Unix and Unix-like systems (such as Linux) Public voidfixtimeexecution () {System.out.println ("At specified time" + Dateformat.format (NewDate ()) + "? Execution"); }}
2> Configuration class
Package Com.wisely.highlight_spring4.ch3.taskscheduler; Import Org.springframework.context.annotation.ComponentScan; Import org.springframework.context.annotation.Configuration; Import org.springframework.scheduling.annotation.EnableScheduling, @Configuration @componentscan (" Com.wisely.highlight_spring4.ch3.taskscheduler "// turn on support for scheduled Tasks public Class taskschedulerconfig {}
3> run
Package Com.wisely.highlight_spring4.ch3.taskscheduler; Import Org.springframework.context.annotation.AnnotationConfigApplicationContext; Public class Main { publicstaticvoid main (string[] args) { = New Annotationconfigapplicationcontext (taskschedulerconfig. Class);} }
Spring Boot Tutorial 11--Scheduled Tasks