springboot 开启定时任务
时间: 2023-09-11 07:13:00 浏览: 130
要在Spring Boot中开启定时任务,你可以按照以下步骤进行操作:
1. 在启动类上使用`@EnableScheduling`注解来开启定时任务功能。例如:
```java
@SpringBootApplication
@EnableScheduling
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
```
2. 在需要定时执行的方法上添加`@Scheduled`注解,并指定cron表达式来设置定时任务的触发时间。例如:
```java
@Scheduled(cron = "*/6 * * * * ?")
public void sayHello() {
System.out.println("hello");
}
```
上述示例中的`cron = "*/6 * * * * ?"`表示每隔6秒执行一次`sayHello()`方法。
这样,当你启动Spring Boot应用程序时,定时任务将自动开始执行。注意,定时任务的触发时间是按照cron表达式来设定的,根据你的需求进行调整即可。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [SpringBoot实现定时任务的三种方式](https://blog.csdn.net/m0_67401761/article/details/126114619)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [Spring boot开启定时任务的三种方式](https://blog.csdn.net/qianlixiaomage/article/details/106599951)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [玩转SpringBoot之定时任务详解](https://blog.csdn.net/weixin_30376163/article/details/97999503)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文