doucan4873 2016-02-05 11:19
浏览 13
已采纳

Golang中的持久性调度

I'm writing a simple notification service i Go. The service provides a REST api where one can put notifications, for instance

{
   delayUntil: '2016-02-05T18:00:00'
   user: 'username',
   msg: 'Hello World',
   isSent: false
}

Now I would like to send a notification to the user at time delayUntil with the requirement that the service should work even if it restarted which means I have to persist the notification. Right now I'm using BoltDB (key/value store).

One way to solve this is to continuously read the DB and send a notification where the delayUntil has passed.

Another way could be to read the DB on service start, and put each notification in a goroutine which fires at the delayUntil time. After the message has been sent, it is marked as Sent in the DB. New entries coming in to the API are inserted into the DB and scheduled.

Is there a preferred/better/simpler way to achieve this?

Edit: Only one instance is required.

  • 写回答

1条回答 默认 最新

  • dounaidu0204 2016-02-05 12:37
    关注

    If you don't want to use external tools and one instance is enough, you could:

    1. Read the DB on service start and put all pending notifications in a list
    2. Sort the list by delayUntil and get the time t of the next (earliest) notification.
    3. Sleep until t, wake up, send all notifications where delayUntil >= t in their own goroutine, delete them from the list and the DB.
    4. Repeat with step 2.

    That's very roughly how cron works. Of course you have to handle insertions and other special cases. Have a look at https://github.com/robfig/cron/blob/master/cron.go to get started.

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题