Scheduler定时任务动态实现-记录

1.定义线程池

	@Bean("sp-syncScheduler")
    public ThreadPoolTaskScheduler syncScheduler() {
        ThreadPoolTaskScheduler syncScheduler = new ThreadPoolTaskScheduler();
        syncScheduler.setPoolSize(5);
        syncScheduler.setThreadGroupName("sp");
        syncScheduler.setThreadNamePrefix("spThread-");
        syncScheduler.initialize();
        return syncScheduler;
    }

2.定义任务服务类

@Service
@Slf4j
@RequiredArgsConstructor
public class SpDynamicTaskService {

    /**
     * 以下两个都是线程安全的集合类。
     */
    public Map<String, ScheduledFuture<?>> taskMap = new ConcurrentHashMap<>();

    public Map<String, SpTaskDo> taskDoMap = new HashMap<>();

    @Resource(name = "sp-syncScheduler")
    private ThreadPoolTaskScheduler syncScheduler;

    private final String IDENTIFY_TASK_TIME = "0/5 * * * * ?";

    private final String TASK_NAME = "任务名称";

    private final String CAPTURE_TASK_TIME = "0 30 8 * * ? ";


    /**
     * 查看已开启但还未执行的动态任务
     * @return
     */
    public SpTaskDto getTask() {
        Set<Map.Entry<String, SitePlotTaskDo>> set = taskDoMap.entrySet();
        SpTaskDto taskDto = new SpTaskDto();
        for (Map.Entry<String, SpTaskDto> stringSpTaskDoEntry : set) {
            taskDto.setTaskName(stringSitePlotTaskDoEntry.getValue().getTaskName());
            taskDto.setCron(stringSitePlotTaskDoEntry.getValue().getCron());
            taskDto.setLastExecutionTime(stringSitePlotTaskDoEntry.getValue().getLastExecutionTime());
            taskDto.setNextExecutionTime(stringSitePlotTaskDoEntry.getValue().getNextExecutionTime());
            return taskDto;
        }
        return taskDto;
    }

    @PostConstruct
    public void taskInit(){
        log.info("===================定时任务初始化===================");
        SpTaskDo spTaskDo = new SpTaskDo();
        spTaskDo.setTaskName(TASK_NAME);
        spTaskDo.setCron(CAPTURE_TASK_TIME);
        this.add(spTaskDo);
    }

    /**
     * 添加一个动态任务
     *
     * @param task
     * @return
     */
    public Response add(SpTaskDo task) {
        if (null != taskMap.get(task.getTaskName())) {
            stop(task.getTaskName());
        }
        ScheduledFuture<?> scheduleCapture = syncScheduler.schedule(getCaptureRunnable(task), new CronTrigger(task.getCron()));
        taskMap.put(task.getTaskName(), scheduleCapture);
        Date date = DateUtils.addSeconds(new Date(), Long.valueOf(scheduleCapture.getDelay(TimeUnit.SECONDS)).intValue());
        task.setLastExecutionTime(DateUtil.formatDateTime(date));
        task.setNextExecutionTime(task.getLastExecutionTime());
        taskDoMap.put(task.getTaskName(), task);
        return Response.buildSuccess();
    }


    /**
     * 定时任务执行
     * @param task
     * @return
     */
    public Runnable getCaptureRunnable(SpTaskDo task) {
        return () -> {
            log.info("---任务运行开始---");
            // TODO 做自己的业务
            task.setLastExecutionTime(task.getNextExecutionTime());
            LocalDateTime nextFirst = CronExpression.parse(task.getCron()).next(LocalDateTime.now());
            DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            task.setNextExecutionTime(dtf2.format(nextFirst));
            taskDoMap.put(task.getTaskName(), task);
            log.info("---任务运行结束---");
        };
    }

    /**
     * 停止任务
     *
     * @param name
     * @return
     */
    public Response stop(String name) {
        if (null == taskMap.get(name)) {
            return Response.buildFailure("500", "任务不存在");
        }
        ScheduledFuture<?> scheduledFuture = taskMap.get(name);
        scheduledFuture.cancel(true);
        taskMap.remove(name);
        taskDoMap.remove(name);
        return Response.buildSuccess();
    }

3.任务实体

@Data
public class SpTaskDo {

    /**
     * 动态任务名
     */
    private String taskName;

    /**
     * 设定动态任务
     */
    private String cron;

    /**
     * 上次执行时间
     */
    private String lastExecutionTime;

    /**
     * 下次执行时间
     */
    private String nextExecutionTime;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 可以使用Flask-APScheduler在MongoDB中实现定时任务,只需要在Flask应用中定义一个定时任务,并将其配置为在MongoDB中运行。具体代码如下:from flask_apscheduler import APSchedulerscheduler = APScheduler()# Configure the scheduler to use MongoDB as its job store scheduler.add_jobstore('mongodb', host='localhost', database='your_database_name')@scheduler.task('interval', id='do_job_1', seconds=30) def job_1(): print("Job 1 executed")@scheduler.task('cron', id='do_job_2', day_of_week='mon-sun', hour='12', minute='30') def job_2(): print("Job 2 executed")# Start the scheduler scheduler.start() ### 回答2: 要使用Flask-APScheduler实现数据库MongoDB定时任务,首先需要安装Flask-APScheduler和pymongo库。在Flask应用程序中,可以使用以下代码实现: 1. 首先,在app.py文件中导入所需的模块和库: ```python from flask import Flask from flask_apscheduler import APScheduler from pymongo import MongoClient ``` 2. 创建Flask应用程序实例: ```python app = Flask(__name__) ``` 3. 配置MongoDB连接并创建MongoDB客户端: ```python app.config['MONGO_URI'] = 'mongodb://localhost:27017/db_name' mongo_client = MongoClient(app.config['MONGO_URI']) ``` 请注意,`db_name`应替换为你的实际数据库名称,`localhost:27017`应替换为你的MongoDB服务器地址和端口。 4. 初始化APScheduler实例并配置任务存储: ```python scheduler = APScheduler() scheduler.init_app(app) scheduler.start() ``` 5. 创建一个定时任务函数,该函数将执行需要定时执行的操作。这里以向MongoDB数据库中插入一条记录为例: ```python def insert_data(): db = mongo_client.db_name collection = db.collection_name data = {'name': 'John', 'age': 30} collection.insert_one(data) ``` 请注意,`db_name`和`collection_name`应替换为你的实际数据库和集合名称。 6. 创建一个定时任务,并将其添加到APScheduler中: ```python scheduler.add_job(func=insert_data, trigger='interval', seconds=60) ``` 这将每隔60秒执行一次`insert_data`函数。 7. 最后,在Flask应用程序的入口处,启动Flask应用程序: ```python if __name__ == '__main__': app.run() ``` 以上代码片段演示了如何使用Flask-APScheduler和pymongo库实现数据库MongoDB定时任务的基本步骤。根据实际需求,你可以根据需要调整设置和任务函数。 ### 回答3: 要使用Flask-APScheduler实现MongoDB数据库的定时任务,需要先安装Flask和Flask-APScheduler库,并且确保MongoDB数据库已经正确安装和配置。 首先,在Flask应用中导入所需要的库和模块: ```python from flask import Flask from flask_apscheduler import APScheduler from pymongo import MongoClient ``` 然后,创建Flask应用和APScheduler实例并配置MongoDB数据库的连接: ```python app = Flask(__name__) scheduler = APScheduler() scheduler.init_app(app) # 配置MongoDB数据库连接 client = MongoClient('mongodb://localhost:27017/') # 替换为实际的MongoDB连接地址 db = client['mydatabase'] # 替换为实际的数据库名称 ``` 接下来,创建一个定时任务函数,该函数在特定时间间隔内会被调度执行,并且可以在函数中访问MongoDB数据库: ```python @scheduler.task('interval', id='my_job', minutes=30) def my_task(): collection = db['mycollection'] # 替换为实际的集合名称 # 在此处添加需要执行的MongoDB操作,例如插入、更新、删除等 # 例如:collection.insert_one({"name": "example"}) ``` 最后,启动定时任务调度器和Flask应用: ```python @app.route('/') def index(): return 'Flask-APScheduler MongoDB Demo' if __name__ == '__main__': scheduler.start() app.run() ``` 启动应用后,定时任务会按照预定的时间间隔执行,并且可以在`my_task()`函数中进行MongoDB的操作。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值