In our project development process, often need to help us to do some of the tasks, springboot default has been implemented for us, only need to add the corresponding annotations can be implemented
1, POM package configuration
Pom Bag only need to introduce Springboot starter package can
<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< Span class= "NT" ></optional></dependency></dependencies>
2. Startup class Enable timing
On start-up class plus to @EnableScheduling
turn on timing
@SpringBootApplication@EnableSchedulingpublic class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);}}
3. Create a timed Task implementation class
Scheduled Task 1:
@Component public class schedulertask {private int Count=0 @Scheduled (cron= "*/6 * * * * *?" ) private void process () {system.. ( "This is scheduler task runing" + (count< Span class= "O" >++)); } /span>
Scheduled Task 2:
@ComponentPublicClassScheduler2task{PrivateStaticFinalSimpleDateFormatdateformat = new simpledateformat ( "HH:mm:ss" @Scheduled (fixedrate = 6000< Span class= "O" >) public void reportcurrenttime ( ) {system.. ( "now time:" + dateformat.< Span class= "NA" >format (new date ())); } /span>
The results are as follows:
this is scheduler task runing 0现在时间:09:44:17this is scheduler task runing 1现在时间:09:44:23this is scheduler task runing 2现在时间:09:44:29this is scheduler task runing 3现在时间:09:44:35
Parameter description
@Scheduled
Parameters can accept two timing settings, one that we commonly use, and the other cron="*/6 * * * * ?"
is that fixedRate = 6000
both represent printing every six seconds.
Fixedrate description
@Scheduled(fixedRate = 6000)
: Executes 6 seconds after the last start point of execution
@Scheduled(fixedDelay = 6000)
: Executed 6 seconds after the last execution time.
@Scheduled(initialDelay=1000, fixedRate=6000)
: Executes 1 seconds after the first delay, followed by fixedrate rules every 6 seconds
Sample Code-github
Sample code-Cloud Code
Springboot (ix): Scheduled Tasks