dounai9294 2019-05-31 03:44
浏览 89
已采纳

每次计时器结束时运行功能的最有效方法,但是使用大量计时器(千/百万)

I'm running a service where users upload a duration and a function must be repeatedly executed every time the timer runs out.

For example, the user says "Run every 5 minutes" and then this function must be run every 5 minutes. This is done through an API.

For a small numbers of timers, this is trivial:

func doEvery(d time.Duration, f func(time.Time)) {
    for x := range time.Tick(d) {
        f(x) // Run the function every d duration
    }
}

I can run each timer in a goroutine, and that works fine. I can start and stop everything with some basic WaitGroups and sync functionality.

But what if I have thousands or millions of timers? I can create a goroutine for each one, but that feels very inefficient. This isn't Erlang.

Should I have multiple work queues, sorted by the "delay", and simply allocate more workers for the more frequent functions? If the timer isn't ready, then it's put back on the queue.

This also isn't ideal, because the workers are busy-waiting (popping off, checking times, pushing on the queue) rather than blocking until the next timer finishes.

Maybe I could have some sort of map, indexed by the remaining duration? I'm not sure what the best approach is here.

  • 写回答

1条回答 默认 最新

  • dougou7782 2019-05-31 04:43
    关注

    I recently built this kind of solution where the user gets notification based on their interval settings. I make a worker pool model using rabbitMQ and two go script. Where one go script uses below cron module to create jobs in a message queue

    https://github.com/robfig/cron

    Another go script is the worker script consuming message queue and taking action. To scale, I'm running multiple instances of worker script. Autoscale of worker script can be done by the number of messages in rabbitMQ

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大