Spring Boot timing tasks

1. Usage scenarios

A timed task needs to be added to the program, and the timed task should be started with the start of the program without additional triggering 

2. References

The following link is a complete copy of the content of this article, used as a backup, intrusion and deletion

https://blog.csdn.net/m0_37885618/article/details/77196691

3. Spring boot instance

@Configuration
@EnableScheduling
public class SchedulingConfig {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Resource 
    private RobotRestServiceImpl robotRestService;

    @Scheduled(cron = "0 0/10 * * * ?") // 每10分钟执行一次
    public void getToken() {
        logger.info("getToken定时任务启动");
    }

illustrate:

A class with @Configuration on the class is equivalent to spring's XML configuration file. The advantage is that type safety can be checked using Java code. Other annotations are usually used to achieve different requirements, such as @EnableScheduling in this example.

In spring-boot, you need to add the @EnableScheduling annotation to the class to enable support for scheduled tasks.

After enabling support for scheduled tasks, the @Scheduled annotation is required. @Scheduled is an annotation on a method, and the method that adds this annotation is a single scheduled task. The @Scheduled annotation defines the execution plan of the scheduled task. There are two ways to define it: 
1. @Scheduled(fixedRate = 5000) //Declare the method as a scheduled task through @Scheduled, and use the fixedRate attribute to execute it every 5 seconds at a fixed time 
2.@Scheduled(cron = "0 0/10 * * * ?") //Use the cron attribute to execute at the specified time, in this case, it means every 10 minutes;

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325318178&siteId=291194637