Tuesday, July 13, 2010

Using Clockwork and Delayed Job gem to send event reminder emails.

code below run a background process to send an event reminder emails.
Install clockwork and delayed_job gem. You might want to upgrade ruby gem version too
commands:
gem install clockwork
gem install delayed_job

Create Reminder model with event_id, reminder_at fields

class CreateReminders < ActiveRecord::Migration
  def self.up
    create_table :reminders do |t|
      t.integer :event_id
      t.datetime :reminder_at
      t.timestamps

    end
  end

  def self.down
    drop_table :reminders
  end
end


Add the association into Reminder model
belongs_to :event

Now create clock.rb in the lib folder of your application and add the following.

  require 'rubygems'
require 'clockwork'
include Clockwork

require 'config/boot'
require 'config/environment'
every(2.minutes, 'reminder.deliver') {
reminders = Reminder.find(:all, :conditions => ["reminder_at <= ? and reminder_at > ?", Time.now.advance(:minutes => 2), Time.now])
#reminders = Reminder.find(:all, :conditions => ["reminder_at <= ?", #Time.now.advance(:minutes => 2)])
unless reminders.nil?
UserMailer.send_later( :deliver_event_reminder, reminders )
end


Now using command prompt go to the root directory of the application and run the command
clockwork lib/clock.rb
If you are using delayed_job then you will have to  rake jobs:work in another command prompt
This will trigger an event every 2 minutes which will get all the reminders that needs to be send in the next two minutes and delivers it.

No comments:

Post a Comment