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 slam rangenet++配置
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊