1. Import the necessary dependencies in Pom.xml:
<parent> <groupId>org.springframework.boot</groupId> <artifactId> spring-boot-starter-parent</artifactid> <version>2.0. 1. release</version> </parent> <dependencies> <!--springboot Core Components-- < dependency> <groupId>org.springframework.boot</groupId> <artifactId> spring-boot-starter-web</artifactid> </dependency> <dependency> <groupid >org.springframework.boot</groupId> <artifactid>spring-boot-starter-tomcat</artifactid > </dependency> </dependencies>
2. Write a Springboot startup class:
Import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.enableautoconfiguration;import Org.springframework.context.annotation.componentscan;import org.springframework.scheduling.annotation.EnableScheduling; @ComponentScan (Basepackages= {"Com.xwj.tasks"}) @EnableScheduling//turn on timed tasks@EnableAutoConfiguration Public classApp { Public Static voidMain (string[] args) {Springapplication.run (App.class, args); }}
Note that it is important to add @EnableScheduling annotations to enable scheduled tasks
3. Start writing Scheduled tasks:
Import Org.springframework.scheduling.annotation.scheduled;import org.springframework.stereotype.component;@ Componentpublicclass ScheduleTask { $) // @Scheduled (cron = "0 23-25 * *?") Public void Testschedule () { System. out. println (" timed task:" + System.currenttimemillis ());} }
Explain:
@Scheduled Notes:
1, fixedrate at a fixed rate of execution. The above means to execute every 1 seconds
2, Fixeddelay and above a task start time is the baseline, from the previous task started after the execution of the call
3, cron expression. Can implement a timed call, the expression configuration can refer to the corn expression--for setting the timing of any
In the use of the process, the landlord felt that if there is only one scheduled task,fixedrate and fixeddelay effect is the same
Springboot's timed task @scheduled