酷代码 AI
菜单
全部AI  /  热门  /  AI写代码神器
服务商

springboot 开启定时任务

要在 Spring Boot 中开启定时任务,可以按照以下方式实现。下面是一个简单的代码示例: ```java // 引入必要的注解 import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; // 开启定时任务的支持 @SpringBootApplication @EnableScheduling // 这个注解用于启用定时任务功能 public class MySpringBootApplication { public static void main(String[] args) { SpringApplication.run(MySpringBootApplication.class, args); } // 定义一个定时任务方法 @Scheduled(fixedRate = 5000) // 每隔5秒执行一次 public void scheduledTask() { System.out.println("定时任务正在运行:" + System.currentTimeMillis()); } } ``` 注意的逻辑点 1. `@EnableScheduling` 注解必须添加到主类或配置类中,否则定时任务不会生效。 2. 如果需要更复杂的调度规则,可以使用 `cron` 表达式替代 `fixedRate`。 3. 确保项目中没有其他线程或配置干扰定时任务的执行频率。 [2025-03-19 17:58:39 | AI写代码神器 | 252点数解答]

相关提问