ThreadPoolTaskScheduler spring boot demo
时间: 2023-07-14 11:06:20 浏览: 68
你好!以下是一个使用ThreadPoolTaskScheduler在Spring Boot中实现任务调度的简单示例:
首先,确保你的Spring Boot项目已经添加了相关的依赖。在pom.xml文件中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-task</artifactId>
</dependency>
```
接下来,创建一个任务调度类,命名为TaskSchedulerConfig.java:
```java
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
@EnableScheduling
public class TaskSchedulerConfig {
@Scheduled(fixedRate = 1000) // 每隔1秒执行一次任务
public void scheduleTask() {
System.out.println("执行任务...");
}
@Scheduled(cron = "0 0 12 * * ?") // 每天中午12点执行任务
public void scheduleTaskWithCronExpression() {
System.out.println("执行定时任务...");
}
// 创建一个ThreadPoolTaskScheduler bean
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(10); // 设置线程池大小
scheduler.setThreadNamePrefix("ThreadPoolTaskScheduler-");
return scheduler;
}
}
```
在上述示例中,我们使用`@Scheduled`注解来指定任务的调度方式。`fixedRate`属性表示以固定的频率执行任务,`cron`属性可以使用Cron表达式来指定任务的调度时间。
最后,在你的Spring Boot应用程序的入口类中添加`@EnableScheduling`注解,以启用任务调度功能:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
```
这就是一个简单的使用ThreadPoolTaskScheduler实现任务调度的Spring Boot示例。希望对你有所帮助!如有更多问题,请随时提问。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)