rschmukler/agenda — pull request #96 by nwkeeley (2014-10-01 19:52:37+00:00)
Title: New feature for jobs: job.unique()

Here is a new feature for working with jobs called .unique(). The purpose of .unique() is that the user can pass properties along with job.create() and it will ensure that there are no other jobs that match those properties.

Best described with a case study:
Within my system at any point in time an alert job may be created. When the "alert" task definition processes the job it can create several new jobs depending on the users preferences (push alert, sms alert, email alert etc..)

Between the hours of 10pm and 10am no sms/email/push should be sent to the user. Rather they should be delayed until the next available alert time. (Example: an alert comes in at 3:00am it should be .schedule() to run at 10:00am.)

Now what I didn't want to happen was X number of alerts to come in at 3:00am and all get scheduled to run at 10:00am and spam the user. The user should only get 1 sms, email and push. I also didn't want to have to run a query to see if a 10:00am sms, email and push already exists for this user every time an alert task definition is ran. So I created the .unique() which when creating the job will do a findAndModify with an upsert with the properties you defined in .unique()

Example
agenda.create('sms alert', {'data.userId': user._id}).unique({'data.userId': user._id, nextRunAt: time}).schedule(time).save();

This will ensure that there is only ever one sms alert for this user for this specified nextRunAt time.

commit 64612da008329c92358bcd4ebff7899320c4b1e9
Author: Nate Keeley
Date: Tue Sep 30 13:17:06 2014 -0400

Unique Job Documentation

commit ea58a4b1a708d15f3ba299bcd331b0bf36115304
Author: Nate Keeley
Date: Tue Sep 30 13:15:50 2014 -0400

Unique Job Code

commit 1655139b9c670578e264823114ec4b3c9f81806c
Author: Nate Keeley
Date: Tue Sep 30 13:15:34 2014 -0400

Unique Job Tests