Springboot 根据数据库生成动态定时任务
时间: 2024-01-13 14:12:58 浏览: 53
可以使用 Spring Boot 中的定时任务框架 `@Scheduled` 来实现动态定时任务。具体步骤如下:
1. 创建一个实体类,用于存储定时任务的相关信息,如任务名、Cron表达式等。
2. 创建一个数据库表,用于存储定时任务的相关信息。
3. 在 Spring Boot 中创建一个定时任务管理器,用于启动、停止和删除定时任务。
4. 使用 Spring Data JPA 或 MyBatis 等持久化框架,从数据库中读取定时任务的相关信息,并使用 `@Scheduled` 注解创建对应的定时任务。
5. 提供接口,允许用户通过 API 的方式添加、修改或删除定时任务。
下面是一个简单的示例:
1. 定义实体类:
```java
@Entity
public class Task {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String cron;
// 省略Getter和Setter
}
```
2. 创建数据库表:
```sql
CREATE TABLE `task` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`cron` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
```
3. 创建定时任务管理器:
```java
@Component
public class TaskScheduler {
private static final Logger logger = LoggerFactory.getLogger(TaskScheduler.class);
private final ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
public TaskScheduler() {
scheduler.setThreadNamePrefix("task-thread-");
scheduler.setPoolSize(10);
scheduler.initialize();
}
public void scheduleTask(Task task) {
logger.info("Schedule task: {}", task.getName());
scheduler.schedule(() -> {
// TODO: 执行定时任务的代码
logger.info("Task executed: {}", task.getName());
}, new CronTrigger(task.getCron()));
}
public void cancelTask(Task task) {
logger.info("Cancel task: {}", task.getName());
scheduler.getScheduledThreadPoolExecutor().getQueue().stream()
.filter(taskScheduledFuture -> {
Object taskToRun = taskScheduledFuture.getTask();
return taskToRun instanceof ScheduledMethodRunnable
&& ((ScheduledMethodRunnable) taskToRun).getMethod().getName().equals(task.getName());
})
.findFirst()
.ifPresent(taskScheduledFuture -> taskScheduledFuture.cancel(true));
}
}
```
4. 使用 `@Scheduled` 注解创建定时任务:
```java
@Service
public class TaskService {
private final TaskRepository taskRepository;
private final TaskScheduler taskScheduler;
public TaskService(TaskRepository taskRepository, TaskScheduler taskScheduler) {
this.taskRepository = taskRepository;
this.taskScheduler = taskScheduler;
}
@Scheduled(fixedRate = 5000)
public void pollTasks() {
List<Task> tasks = taskRepository.findAll();
for (Task task : tasks) {
taskScheduler.scheduleTask(task);
}
}
}
```
5. 提供接口,允许用户操作定时任务。
参考资料:
- [Spring Boot 定时任务的实现](https://www.jianshu.com/p/ce4784bb863c)
- [Spring Boot 定时任务详解](https://www.jianshu.com/p/9f6e385a4a2e)
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)