Rails Plugin - Acts As Scheduled
I’ve just released the first pass of a Ruby on Rails Plugin called Acts As Scheduled.
acts_as_scheduled allows you to manage scheduled events for your models.
A good example of this is scheduling the update of RSS Feeds in a background process using Cron or BackgroundRB.
With acts_as_scheduled your schedule manager can simply call “Model.find_next_scheduled()” to grab the next item from the database.
At the moment it assumes you are working with MySQL.
All you need to get started is to add two extra columns to your table:
t.integer frequency
t.datetime last_scheduled
frequency is the number of seconds for your schedule.
last_scheduled is the date and time the record was last processed.
Ruby on Rails is real smart with times, so you don’t have to worry too much about calculating frequency values:
model.frequency = 1.day
model.frequency = 1.minute
model.frequency = 10.second
In your model class your simply declare “acts_as_scheduled” and you now have two extra methods find_next_scheduled and schedule_complete.
find_next_scheduled
Returns the next scheduled record from the table.
The next scheduled record is calculated as “the record who’s last_scheduled value is less than the current time minus the specified frequency in seconds”.Which is the complex way of saying “if freqency is 1 minute, return the record if it was last_scheduled more than 1 minute ago”
If there is more than one record, records scheduled to occur more frequently will be handled first (so records with minute schedules are returned before records with daily schedules.
schedule_complete
Sets the record’s last_scheduled value to Time.now
Example
class ScheduledItem < ActiveRecord::Base
acts_as_scheduled
endschedule_minute = ScheduledItem.new(:frequency => 1.minute, :last_scheduled => 2.seconds.ago)
schedule_minute.saveschedule_day = ScheduledItem.new(:name =>”day”, :frequency => 1.day, :last_scheduled => 25.hours.ago)
schedule_day.save#returns thing_day because it was last_scheduled 25 hours ago
schedule_day = ScheduledItem.find_next_scheduled
schedule_day.do_some_stuff
schedule_day.schedule_complete
schedule_day.save