Spring动态管理定时任务——ThreadPoolTaskScheduler

Spring任务调度核心类ThreadPoolTaskScheduler,API文档解释如下:

Implementation of Spring's TaskScheduler interface, wrapping a native java.util.concurrent.ScheduledThreadPoolExecutor.

Spring的TaskScheduler接口的实现,包装了一个本地java.util.concurrent.ScheduledThreadPoolExecutor。

实现思路

注入调度类bean,初始化一个ConcurrentHashMap容器,用来保存多个定时任务的状态,每一个任务的运行状态被封装在ScheduledFuture中,借此类可取消对应的定时任务。

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cjia.spidercommon.model.SpiderJob;
import com.cjia.spiderjob.mapper.SpiderJobMapper;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * 用来管理(启动、停止、新增、删除、更新编辑、查看运行状态)定时任务(增量任务)
 */
@Slf4j
@RestController
@RequestMapping("spiderJob/cron")
public class CronJobController extends SpiderJobController {

    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private Map> futureMap = new ConcurrentHashMap<>();

    @Resource
    private SpiderJobMapper spiderJobMapper;

    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
        return new ThreadPoolTaskScheduler();
    }

    /**
     * 启动单个定时任务
     */
    @RequestMapping("/start/{jobId}")
    public String start(@PathVariable Integer jobId) {
        SpiderJob job = spiderJobMapper.selectById(jobId);
        if (job == null) {
            log.warn("任务[{}]已不存在,无法启动!", jobId);
            return "任务[" + jobId + "]已不存在,无法启动!";
        }
        int enable = job.getEnable();
        if (enable == 0) {
            log.warn("任务[{}]已被禁用,无法启动!", jobId);
            return "任务[" + jobId + "]已被禁用,无法启动!";
        }
        // 检测该任务是否已在运行调度中
        if (futureMap.get(jobId) != null) {
            log.warn("任务[{}]已在调度运行,无法重复启动!", jobId);
            return "任务[" + jobId + "]已在调度运行,无法重复启动!";
        }
        String cron = job.getCron();
        // TODO check cron
        ScheduledFuture future = threadPoolTaskScheduler.schedule(new MyRunnable(job), new CronTrigger(cron));
        log.info("任务[{}]已被启动!", jobId);
        futureMap.put(jobId, future);
        return "任务[" + jobId + "]已被启动!";
    }

    /**
     * 批量启动定时任务
     */
    @RequestMapping("/startBatch/{jobIds}")
    public String startBatch(@PathVariable String jobIds) {
        // TODO jobIds valid
        String[] jobIdsArr = jobIds.split(",");
        StringBuffer sb = new StringBuffer();
        for (String jobId : jobIdsArr) {
            String result = start(Integer.valueOf(jobId));
            sb.append(result).append("
"); } return sb.toString(); } /** * 停止单个定时任务 */ @RequestMapping("/stop/{jobId}") public String stop(@PathVariable Integer jobId) { // 检测该任务是否已在运行调度中 ScheduledFuture future = futureMap.get(jobId); if (future == null) { log.warn("任务[{}]已不在调度中,无法停止!", jobId); return "任务[" + jobId + "]已不在调度中,无法停止!"; } else { future.cancel(true); futureMap.remove(jobId); log.info("任务[{}]已被停止!", jobId); return "任务[" + jobId + "]已被停止!"; } } /** * 批量停止定时任务 */ @RequestMapping("/stopBatch/{jobIds}") public String stopBatch(@PathVariable String jobIds) { // TODO jobIds valid String[] jobIdsArr = jobIds.split(","); StringBuffer sb = new StringBuffer(); for (String jobId : jobIdsArr) { String result = stop(Integer.valueOf(jobId)); sb.append(result).append("
"); } return sb.toString(); } /** * 查看当前时刻调度中的定时任务 */ @RequestMapping("/status") public String getAllStatus() { Set runningKeys = futureMap.keySet(); return "当前正在调度的任务列表:" + runningKeys.toString(); } @Data private class MyRunnable implements Runnable { private SpiderJob job; public MyRunnable(SpiderJob job) { this.job = job; } @Override public void run() { log.info("运行定时任务[{}: {}] at {}!", job.getId(), job.getBizName(), LocalDateTime.now()); executeIncrementJob(job.getBizName()); } } }

另附:

ThreadPoolTaskScheduler 使用的注意事项

springboot自定义定时任务(不能动态增删改等管理)

你可能感兴趣的:(Spring)