This article describes the use of Springboot timed tasks, springboot by default has been implemented for us, only need to add the corresponding annotations can be implemented.
1.pom configuration file
Pom Bag only need to introduce springboot starter bag.
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starter-test</ artifactid> <scope>test</scope> </dependency> <dependency> < Groupid>org.springframework.boot</groupid> <artifactid>spring-boot-devtools</artifactid > <optional>true</optional> </dependency></dependencies>
2. Startup class Enable timing
The timer can be turned on by adding @enablescheduling to the Startup class.
@SpringBootApplication@EnableScheduling Public class springbootapplication { publicstaticvoid main (string[] args) { Springapplication.run (springbootapplication. class , args);} }
3. Create a timed Task implementation class
Import Java.text.simpledateformat;import Java.util.date;import Org.springframework.scheduling.annotation.scheduled;import org.springframework.stereotype.Component; @Component Public classSchedulertask {Private intCount=0; Private StaticFinal SimpleDateFormat DateFormat =NewSimpleDateFormat ("HH:mm:ss"); @Scheduled (Cron="*/6 * * * *?") Private voidprocess () {System. out. println ("This is Scheduler task runing"+ (count++)); } @Scheduled (Fixedrate=6000) Public voidReportcurrenttime () {System. out. println ("Current Time:"+ Dateformat.format (NewDate ())); } }
Parameter description:
@Scheduled parameter can accept two kinds of timing settings, one is our common cron= "*/6 * * * *?", one is fixedrate = 6000, both of which represent every six seconds to print the content.
Fixedrate description
@Scheduled (fixedrate = 6000): Executes 6 seconds after the last execution point;
@Scheduled (Fixeddelay = 6000): Executed 6 seconds after the last execution time;
@Scheduled (initialdelay=1000, fixedrate=6000): Executes after the first delay of 1 seconds, followed by the rules of fixedrate every 6 seconds.
Console output:
If a static variable is used, the private static Boolean isstop=false is assumed;
In the method of the timer, the first line plus a line of code: if (isstop) return;
If you need to stop the timer, you write a page, control the value of the isstop can switch the timer.
⑤springboot's Scheduled Tasks