Execute Action at a Specified Time

Hey all.
I’m creating an app that that involves sending emails at a specified
date-time. I only have one model and it has a “sendat” (:datetime)
column. I need to send an email to an email address (also in the
model) at the “sendat” time. I’m not sure how to do this.

On Oct 6, 2007, at 16:31 , David wrote:

I need to send an email to an email address (also in the
model) at the “sendat” time.

Run a script/runner via cron job that checks for emails that need to
be sent and sends them. I’m thinking something along the lines of
“send emails with sendat < now that haven’t been sent”.

Michael G.
grzm seespotcode net

Heres my method in my Item model:


def self.send_expired
items = Item.find(:all, :conditions => [“time <= ?”, Time.now])

for item in items
email = item.email
content = item.content

time = item.time.strftime("%b %d %I:%M %p")

begin
  Notifier.deliver_item_email(email, content, time)
rescue Exception => e
  logger.error("Error: e.message")
else
  Item.find(item.id).destroy
end

end

end
**

Here’s my Notifier class:
**
class Notifier < ActionMailer::Base
def item_email(email,content,time)
recipients email
from “[email protected]
subject “You are being notified!”
body :content => content, :time => time
end
end
**

Basically, the self.send_expired method grabs all the Item objects
that have a time column before the current time, sends the item via
email, and deletes it from the db.

The first time I ran “script/runner -e development
‘Item.send_expired’” it worked fine and it sent all the items that had
expired. I then created another item object that had a time 5 minutes
after I saved it to the db. When that time passed (in other words,
when the item “expired”), no email was sent and the item remained in
the db. I guess script/runner only called the ‘send_expired’ method
when I started it.

I guess I don’t really understand how script/runner works. I thought
it continuously calls the function, so as soon as an item expires, it
is sent via email and destroyed. Could someone please explain?

~ David

On 10/11/07, David [email protected] wrote:

I guess I don’t really understand how script/runner works. I thought
it continuously calls the function, so as soon as an item expires, it
is sent via email and destroyed. Could someone please explain?

No, script/runner just runs your code once and then exits. It doesn’t
do anything magic.

Michael suggested you run script/runner periodically from cron (every
5 minutes, or whatever frequency you need). I think that’s the best
solution.

You could also make your runner script check for mails, then sleep for
a while, then check again, in an endless loop.