As we develop projects, we often need timed tasks to help us do something. Spring Boot does this by default, just add annotations
1. Pom package configuration
You only need to import the Spring Boot Starter package to the POM package
<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>
</dependencies>
Copy the code
2. The startup class enables timing
To enable the timer, add @enablesCheduling to the boot class
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main (String [] args ) {
SpringApplication. run( Application. class, args);
}
}
Copy the code
3. Create a scheduled task implementation class
Scheduled Task 1:
@Component
public class SchedulerTask {
private int count=0;
@Scheduled(cron="*/6 * * * * ?" )
private void process(){
System.out.println("this is scheduler task runing "+(count++));
}
}
Copy the code
Scheduled Task 2:
@Component
public class Scheduler2Task {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 6000)
public void reportCurrentTime() {
System.out.println(" dateformat.format (new Date()) ");
}
}
Copy the code
The results are as follows:
this is scheduler task runing 0
Now: 09:44:17
this is scheduler task runing 1
Now: 09:44:23
this is scheduler task runing 2
Now: 09:44:29
this is scheduler task runing 3
Now: 09:44:35
Copy the code
Parameters that
The @scheduled parameter accepts two Scheduled Settings, one of which is the usual cron=”*/6 * * * *?” , one is fixedRate=6000, and both mean that the content is printed every six seconds.
FixedRate instructions
-
@Scheduled (fixedRate =6000) : Execution is Scheduled 6 seconds after the last time it started
-
@scheduled (fixedDelay =6000) : Scheduled is executed 6 seconds after the last time point
-
@Scheduled (initialDelay =1000,fixedRate =6000) : Scheduled (initialDelay =1000,fixedRate =6000) : Executed after the first delay of 1 second and then every 6 seconds according to fixedRate’s rules
The sample code – https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-scheduler
-END-
Java geek technology
Attention to reply Java, send the strongest interview resources