在 Spring Boot 中,我们可以通过在定时任务方法上添加 @Scheduled 注解来实现定时任务的调度,而 @EnableScheduling 注解的作用就是启用 Spring 自带的定时任务调度器,使得 @Scheduled 注解生效。

@EnableScheduling 注解通常需要添加在 Spring Boot 应用的启动类上,例如:

@SpringBootApplication
@EnableScheduling
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

这样,我们就可以在其他类中使用 @Scheduled 注解来定义定时任务了。例如:

@Component
public class MyTask {
    @Scheduled(fixedRate = 5000)
    public void doSomething() {
        // 每隔 5 秒执行一次
    }
}

在上面的代码中,我们在 MyTask 类中定义了一个名为 doSomething 的方法,并在方法上添加了 @Scheduled 注解,指定了该方法需要每隔 5 秒执行一次。由于我们在启动类中添加了 @EnableScheduling 注解,因此这个定时任务会自动被 Spring 框架调度执行。

Spring Boot 定时任务:使用 @EnableScheduling 注解开启调度

原文地址: https://www.cveoy.top/t/topic/n4YH 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录