build project
Create a Springboot project, add @EnableScheduling to its program entry, and enable scheduling tasks.
@SpringBootApplication
@EnableScheduling
public class SpringbootSchedulingTasksApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootSchedulingTasksApplication.class, args);
}
}
Create a scheduled task
Create a timed task that prints the current time on the console every 5s.
@Component
public class ScheduledTasks {
private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
}
By adding the @Scheduled annotation to the method, it is indicated that the method is a scheduled task.
- @Scheduled(fixedRate = 5000) : Execute again 5 seconds after the last execution time point
- @Scheduled(fixedDelay = 5000) : Execute again 5 seconds after the last execution time point
- @Scheduled(initialDelay=1000, fixedRate=5000) : Execute after the first delay of 1 second, and then execute it every 5 seconds according to the rules of fixedRate
- @Scheduled(cron=" /5 ") : Define rules through cron expressions, what is a cro expression, and search the engine by yourself.
test
Start the springboot project, and the console prints the current time within 5s.
2017-04-29 17:39:37.672 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:37
2017-04-29 17:39:42.671 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:42
2017-04-29 17:39:47.672 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:47
2017-04-29 17:39:52.675 INFO 677 — [pool-1-thread-1] com.forezp.task.ScheduledTasks : The time is now 17:39:52
It only takes 2 steps to create a scheduled task in springboot:
- 1. Add the @EnableScheduling annotation to the entry of the program.
- 2. Add the @Scheduled annotation to the timing method.