Scheduled多任务动态定时器学习总结

一:解决的问题场景

1常用的场景是基于数据库配置定时任务id、corn表达式,名称、描述等。

本次忽略数据库,

2原理:

核心是两个map

ConcurrentHashMap<String, ScheduledFuture<?>> scheduledFutures 负责定时任务的取消,关闭,创建,主要是对map中的键值对操作

ConcurrentHashMap<String, CronTask> cronTasks负责接收具体要跑的任务和cron表达式,以及动态刷新cron

3实现:

参考网上例子直接上代码:

import com.example.admin.entity.TaskEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
public class StartController {
    @Autowired
    private MyScheduledTask scheduledTask;

    @PostMapping(value = "/startOrChangeCron")
    public String changeCron(@RequestBody List<TaskEntity> list){
        if (!CollectionUtils.isEmpty(list)) {
            // 这里模拟存在数据库的数据
            scheduledTask.refresh(list);
        }
        return "task任务:" + list.toString() + "已经开始运行";
    }

    @PostMapping(value = "/stopCron")
    public String stopCron(@RequestBody List<TaskEntity> list){
        if (!CollectionUtils.isEmpty(list)) {
            // 这里模拟将要停止的cron可通过前端传来
            scheduledTask.stop(list);
        }
        List<String> collect = list.stream().map(TaskEntity::getTaskId).collect(Collectors.toList());
        return "task任务:" + collect.toString() + "已经停止启动";
    }

}

请求入口

import com.example.admin.entity.TaskEntity;
import org.springframework.bean
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值