首页 > 解决方案 > 在一系列任务中产生更长延迟的更好方法是什么?

问题描述

我正在尝试构建一个工作流系统,它将处理一系列任务和延迟。可以从正在运行的工作流中更改或删除延迟。

在一系列任务中延长延迟的更好方法是什么?(比如 3-4 个月)。现在有两种方法在我脑海中萦绕:

  1. 预先计算并节省延迟时间。设置一个调度程序,将在特定时间间隔(可能 1 分钟)后重复检查延迟。这将进行大量的数据库查询,但延迟可以立即更改。

  2. 安排一个延迟的工作。这可以减少很多数据库查询,但问题是维护和更改这些长时间运行的作业的延迟。此外,这些作业需要在服务器崩溃或重启后幸存下来。

现在我不确定如何以更好的方式做到这一点,并且仍在研究它。如果有人有类似经历,请分享。

标签: node.jscronscheduling

解决方案


You can store the tasks into the database, like :

{
   _id: String,
   status: Enum,
   executionTime: timestamp,
}

When you declare a new task, push a new entry into the DB.


At your server start, or when a new task is declared, create a setTimeout that will wake up your node.js when it's necessary.


Optimization

To avoid having X setTimeout, with X the number of task to execute. Keep only one setTimeout, with the time to wait equals to the closest task to execute.

For example, you have three task, one must run in 1 hour, one in 2 hour and one in 3 hour. Use a setTimeout of 1 hour. When it get triggered, it execute the task 1 and then look at the remaining tasks to re-run.


推荐阅读