olif
olif

Reputation: 3309

Persistent scheduling in 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.

Upvotes: 0

Views: 2330

Answers (1)

fl0cke
fl0cke

Reputation: 2884

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.

Upvotes: 2

Related Questions