1.添加执行定时任务的线程池配置类
package com.fy8.fund.schedule.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
public class ThreadPoolTaskSchedulerConfig {
/**
* 线程池任务调度类
* @return
*/
@Bean
public ThreadPoolTaskScheduler threadPoolTaskScheduler(){
ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
threadPoolTaskScheduler.setPoolSize(10);
threadPoolTaskScheduler.setThreadNamePrefix("ThreadPoolTaskScheduler");
return threadPoolTaskScheduler;
}
}
2.添加 Runnable 接口实现类,被定时任务线程池调用,用来执行指定 bean 里面的方法。
package com.fy8.fund.schedule.task;
import com.fy8.fund.schedule.service.FundService;
import com.fy8.fund.common.entity.Fund;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class FundTask implements Runnable{
@Autowired
private FundService fundService;
@Override
public void run() {
fetchFund();
}
/**
* 间隔1秒执行一次
*/
public void fetchFund() {
List<Fund> fundList = fundService.getFundList();
System.out.println(fundList);
}
}
3.创建任务调度数据库表
CREATE TABLE `schedule_task` (
`id` bigint(0) NOT NULL AUTO_INCREMENT,
`cron` varchar(50),
`target_name` varchar(100),
`name` varchar(100),
`description` varchar(500),
`stats` varchar(10),
PRIMARY KEY (`id`) USING BTREE
);
4.前端页面,创建模板页面index.html,默认要放在resources/templates/index.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>首页</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" th:href="@{/css/index.css}"/>
</head>
<body>
<div class="main">
<div class="main_buttons">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">新增</button>
</div>
<table class="table">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">任务名</th>
<th scope="col">Cron</th>
<th scope="col">TargetName</th>
<th scope="col">状态</th>
<th scope="col">操作</th>
</tr>
</thead>
<tbody>
<tr th:each="task : ${scheduleTaskList}">
<th th:text="${task.id}"></th>
<td th:text="${task.name}"></td>
<td th:text="${task.cron}"></td>
<td th:text="${task.targetName}"></td>
<td th:text="${task.stats}"></td>
<td>
<button type="button" th:onclick="|window.location.href='/fy8/fund/schedule/task/delete/${task.id}'|" class="btn btn-warning">删除</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">新增任务</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="#" method="post" th:action="@{/fy8/fund/schedule/task/add}" th:object="${scheduleTask}">
<div class="form-group">
<label for="exampleInputEmail1">任务名</label>
<input type="text" th:field="*{name}" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="任务名">
</div>
<div class="form-group">
<label for="inputCron">Cron</label>
<input type="text" th:field="*{cron}" class="form-control" id="inputCron" aria-describedby="cronHelp" placeholder="Cron">
<small id="cronHelp" class="form-text text-muted">6位cron 表达式</small>
</div>
<div class="form-group mb-3">
<label for="inputClassName">TargetName</label>
<select class="custom-select" th:field="*{targetName}" id="inputClassName" aria-label="Example select with button addon">
<option selected value="">Choose...</option>
<option th:each="task : ${availableTaskList}"
th:value="${task.key}"
th:text="${task.key + '-' + task.value}"></option>
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
页面效果
5.定时任务管理controller
package com.fy8.fund.schedule.controller;
import com.fy8.fund.schedule.service.ScheduleTaskService;
import com.fy8.fund.common.entity.ScheduleTask;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
/**
* @ClassName ScheduleTaskController
* @Description 定时任务管理Controller
* @Author dhy
* @Date 2020/7/18 22:00
* @Version 1.0
**/
@RestController
@Api(value = "定时任务管理")
@RequestMapping("/fy8/fund/schedule/task")
public class ScheduleTaskController {
@Autowired
ScheduleTaskService scheduleTaskService;
@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView index() {
ModelAndView mav = new ModelAndView("index");
mav.addObject("scheduleTaskList", scheduleTaskService.queryAll());
mav.addObject("availableTaskList", scheduleTaskService.getAvailableTask());
mav.addObject("scheduleTask", new ScheduleTask());
return mav;
}
@PostMapping("/add")
@ApiOperation(value = "新增或者更新定时任务")
public ModelAndView add(ScheduleTask scheduleTask) {
scheduleTaskService.add(scheduleTask);
return new ModelAndView("redirect:/fy8/fund/schedule/task/index");
}
@GetMapping("/delete/{id}")
@ApiOperation(value = "删除定时任务")
public ModelAndView delete(@PathVariable String id) {
scheduleTaskService.remove(id);
return new ModelAndView("redirect:/fy8/fund/schedule/task/index");
}
}
6.对定时任务初始化、新增、删除的具体实现service
package com.fy8.fund.schedule.service;
import com.fy8.fund.common.entity.ScheduleTask;
import com.fy8.fund.common.mapper.ScheduleTaskMapper;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture;
/**
* @ClassName ScheduleTaskService
* @Description 定时任务管理service
* @Author dhy
* @Date 2020/7/18 22:19
* @Version 1.0
**/
@Service
public class ScheduleTaskService {
@Autowired
private ApplicationContext applicationContext;
@Resource
private ScheduleTaskMapper scheduleTaskMapper;
@Resource
private ThreadPoolTaskScheduler executor;//线程池
private Map<String, ScheduledFuture> scheduledFutureMap = Maps.newHashMap();//记录运行中的定时任务
/**
* 启动服务器时,加载全部定时任务,添加进线程池执行
*/
@PostConstruct
public void init() {
List<ScheduleTask> scheduleTasks = scheduleTaskMapper.selectAll();
scheduleTasks.forEach(scheduleTask -> {
if (StringUtils.isEmpty(scheduleTask.getTargetName())) {
return;
}
Runnable targetTask = applicationContext.getBean(scheduleTask.getTargetName(), Runnable.class);
if (targetTask==null){
return;
}
//开始定时任务
ScheduledFuture future = executor.schedule(targetTask, new CronTrigger(scheduleTask.getCron()));
//记录运行中的定时任务
scheduledFutureMap.put(scheduleTask.getTargetName(), future);
});
}
/**
* 查询全部定时任务
* @return 全部定时任务
*/
public List<ScheduleTask> queryAll(){
return scheduleTaskMapper.selectAll();
}
/**
* 查询可配置的定时任务
* @return
*/
public Map<String, String> getAvailableTask() {
Map<String, Runnable> beans = applicationContext.getBeansOfType(Runnable.class);
Map<String, String> ret = Maps.newHashMap();
for (Map.Entry<String, Runnable> bean : beans.entrySet()) {
ret.put(bean.getKey(), bean.getValue().getClass().getName());
}
return ret;
}
/**
* 新增定时任务
* @param task
* @return
*/
public ScheduleTask add(ScheduleTask task) {
scheduleTaskMapper.insert(task);
//启动新增的定时任务
Runnable targetTask = applicationContext.getBean(task.getTargetName(), Runnable.class);
ScheduledFuture future = executor.schedule(targetTask, new CronTrigger(task.getCron()));
scheduledFutureMap.put(task.getTargetName(), future);
return task;
}
/**
* 取消并删除定时任务
* @param id
* @return
*/
public boolean remove(String id) {
if (StringUtils.isEmpty(id)) {
return Boolean.TRUE;
}
try {
ScheduleTask task = new ScheduleTask();
task.setId(Long.parseLong(id));
ScheduleTask scheduleTask = scheduleTaskMapper.selectOne(task);
if (scheduleTask!=null) {
//取消定时任务
ScheduledFuture future = scheduledFutureMap.get(scheduleTask.getTargetName());
if (Objects.nonNull(future)) {
future.cancel(false);
}
//删除定时任务
scheduleTaskMapper.delete(scheduleTask);
}
} catch (Exception e) {
return Boolean.FALSE;
}
return Boolean.TRUE;
}
}