在Golang中的持久调度

huangapple go评论66阅读模式
英文:

Persistent scheduling in Golang

问题

我正在使用Go语言编写一个简单的通知服务。该服务提供一个REST API,可以用来发送通知。例如:

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

现在,我想在延迟时间delayUntil发送通知给用户,并且要求即使服务重启也能正常工作,这意味着我需要持久化通知。目前我正在使用BoltDB(键值存储)。

一种解决方法是不断读取数据库,并在delayUntil时间已过时发送通知。

另一种方法是在服务启动时读取数据库,并将每个通知放入一个goroutine中,在delayUntil时间触发通知。消息发送后,将在数据库中将其标记为已发送。新的API请求会被插入到数据库并进行调度。

是否有更好/更简单的方法来实现这个需求?

编辑: 只需要一个实例。

英文:

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

得分: 2

如果您不想使用外部工具,并且一个实例足够的话,您可以按照以下步骤进行操作:

  1. 在服务启动时读取数据库,并将所有待处理的通知放入一个列表中。
  2. 按照delayUntil对列表进行排序,并获取下一个(最早)通知的时间t
  3. 睡眠直到达到时间t,然后唤醒,在它们自己的goroutine中发送所有满足delayUntil >= t条件的通知,从列表和数据库中删除它们。
  4. 重复执行第2步。

这大致是cron的工作原理。当然,您还需要处理插入和其他特殊情况。您可以参考https://github.com/robfig/cron/blob/master/cron.go来开始。

英文:

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.

huangapple
  • 本文由 发表于 2016年2月5日 19:19:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/35222853.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定