通过线程池设置自定义定时任务
作者:互联网
启动自动运行
Controller
/**
* 启动自动运行
* @param id
* @return
*/
@GetMapping("startAutoRun")
public APIResponse startAutoRun(String id){
try {
managementService.startAutoRun(id);
return new APIResponse(ResponeCode.SUCCESS);
}catch (Exception e){
e.printStackTrace();
return new APIResponse(ResponeCode.FAIL,e.getMessage());
}
}
Service
@Autowired
ApplicationContext applicationContext;
public static Map<String, Timer> timerMap = new HashMap<String, Timer>();
@Service
@EnableAsync
public class InterfaceManagementServiceImpl extends ServiceImpl<InterfaceManagementMapper, InterfaceManagement> implements InterfaceManagementService {
@Override
public void startAutoRun(String id) throws InterruptedException, ExecutionException {
InterfaceManagement management = managementMapper.selectById(id);
if ("1".equals(management.getAuto()) && "0".equals(management.getAutoRun()) && management.getIntervalTime() != 0) {
// AsyncInterfaceManagement asyncInterfaceManagement = new AsyncInterfaceManagement();
AsyncInterfaceManagement asyncInterfaceManagement = applicationContext.getBean(AsyncInterfaceManagement.class);
Future<String> future = asyncInterfaceManagement.async(management.getId(), management.getPath(), management.getIntervalTime(),timerMap);
String threadName = future.get();
management.setAutoRun("1");
management.setThreadName(threadName);
managementMapper.updateById(management);
}
}
}
Async
package diit.resourcemanage.utils;
import lombok.SneakyThrows;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Future;
@EnableAsync
@Component
public class AsyncInterfaceManagement {
//给配置命名 通过@Async注解启动新线程
@Async("threadPoolTaskExecutor")
public Future<String> async(String id, String path, Long intervalTime, Map<String, Timer> timerMap) throws InterruptedException {
//Timer定时任务对象
Timer timer = new Timer(id);
TimerTask timerTask = null;
try {
timerTask = new TimerTask() {
//将要执行的定时任务内容
@SneakyThrows
@Override
public void run() {
HttpClientResult httpClientResult = HttpClientUtil.doGet(path);
System.out.println(httpClientResult.getContent().substring(0, 100));
}
};
} catch (Exception e) {
timer.cancel();
e.printStackTrace();
}
//安排指定的任务在指定的时间开始进行重复的固定延迟执行。这里是每3秒执行一次
//第 二个参数为时间格式毫秒(延迟多少秒后执行一次timerTask)
//第三个参数为时间格式毫秒(隔多长时间执行timerTask一次)
timer.schedule(timerTask, 0, intervalTime * 1000);
timerMap.put(id, timer);
//通过Future 获取异步线程的返回值
return new AsyncResult<>(Thread.currentThread().getName());
}
}
ThreadPoolConfig
package diit.resourcemanage.config;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync // 允许使用异步方法
public class ThreadPoolConfig {
@Bean("threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
// 设置核心线程数
threadPoolTaskExecutor.setCorePoolSize(5);
// 设置最大线程数
threadPoolTaskExecutor.setMaxPoolSize(10);
// 设置工作队列大小
threadPoolTaskExecutor.setQueueCapacity(2000);
// 设置线程名称前缀
threadPoolTaskExecutor.setThreadNamePrefix("autoRun_");
// 设置拒绝策略.当工作队列已满,线程数为最大线程数的时候,接收新任务抛出RejectedExecutionException异常
// threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
//CallerRunsPolicy在任务被拒绝添加后,会用调用execute函数的上层线程去执行被拒绝的任务。
threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化线程池
threadPoolTaskExecutor.initialize();
return threadPoolTaskExecutor;
}
}
关闭自动运行
Controller
@GetMapping("stopAutoRun")
public APIResponse stopAutoRun(String id){
try {
managementService.stopAutoRun(id);
return new APIResponse(ResponeCode.SUCCESS);
}catch (ConcurrentModificationException e){
return new APIResponse(ResponeCode.SUCCESS);
}catch (Exception e){
e.getMessage();
return new APIResponse(ResponeCode.FAIL,e.getMessage());
}
}
Service
@Override
public void stopAutoRun(String id) {
InterfaceManagement management = managementMapper.selectById(id);
for (Map.Entry<String, Timer> entry : timerMap.entrySet()) {
Timer timer = entry.getValue();
//根据之前存储的全局Map获取name然后去除定时任务
if (id.equals(entry.getKey())) {
timer.cancel();
timerMap.remove(entry.getKey());
}
}
management.setAutoRun("0");
management.setThreadName("");
managementMapper.updateById(management);
for (Thread thread : Thread.getAllStackTraces().keySet()) {
//强制停止线程
if (thread.getName().equals(management.getThreadName())) {
thread.stop();
}
}
}
项目启动初始化任务启动状态
CommandLineRunner
package diit.resourcemanage.config;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import diit.resourcemanage.mapper.InterfaceManagementMapper;
import diit.resourcemanage.model.po.InterfaceManagement;
import diit.resourcemanage.service.impl.InterfaceManagementServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.List;
//通过实现CommandLineRunner然后重写run来使服务启动完成后对启动状态初始化
@Component
public class InterfaceManagementInitConfig implements CommandLineRunner {
@Autowired
private InterfaceManagementMapper managementMapper;
@Autowired
private InterfaceManagementServiceImpl interfaceManagementService;
@Override
public void run(String... args) throws Exception {
QueryWrapper<InterfaceManagement> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("auto", "1");
List<InterfaceManagement> managementList = managementMapper.selectList(queryWrapper);
if (managementList.size() != 0){
for (InterfaceManagement management : managementList) {
management.setAutoRun("0");
management.setThreadName("");
}
}
interfaceManagementService.updateBatchById(managementList);
}
}
标签:management,自定义,id,线程,new,import,定时,threadPoolTaskExecutor,public 来源: https://www.cnblogs.com/ideaAI/p/16669090.html