首页 > 解决方案 > 如何使用 DB 数据动态添加或删除 spring 框架的调度程序(服务器处于运行状态)?

问题描述

我正在与 Spring-boot 和 Oracle sql 开发人员合作。我想实现诸如“用户管理调度程序”之类的东西。

用户可以在网页上添加或删除调度程序。如果用户添加“调度程序每 3 分钟运行一次”,则 db 表可能...

s_id | s_cron | s_detail
sid000001 | 0 0/3 * * * ? | do job 1

春季调度程序必须每 3 分钟执行一次“作业 1”。

如果,另一个用户还添加了“调度程序每 1 分钟运行一次”,

s_id | s_cron | s_detail
sid000001 | 0 0/3 * * * ? | do job 1
sid000002 | 0 0/1 * * * ? | do job 2

并且 spring 调度程序必须每 3 分钟执行一次“作业 1”,并且必须同时每 1 分钟执行一次“作业 2”。

问题是:我怎样才能在 Spring-boot 中实现它?Spring 服务必须动态(或自动)添加/删除调度程序,并在服务器运行中添加/删除数据库数据。

请给我一些手。

标签: javaspringspring-bootoracle-sqldeveloperspring-scheduled

解决方案


如果你想动态调度任务,你可以通过使用ExecutorService来实现,特别是ScheduledThreadPoolExecutor

Runnable task  = () -> doSomething();
ScheduledExecutorService executor = 
Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
// Schedule a task that will be executed in 120 sec
executor.schedule(task, 120, TimeUnit.SECONDS);

// Schedule a task that will be first run in 120 sec and each 120sec
// If an exception occurs then it's task executions are canceled.
executor.scheduleAtFixedRate(task, 120, 120, TimeUnit.SECONDS);

// Schedule a task that will be first run in 120 sec and each 120sec after 
the last 
execution
// If an exception occurs then it's task executions are canceled.
executor.scheduleWithFixedDelay(task, 120, 120, TimeUnit.SECONDS);

推荐阅读