I have something that does exactly that.
It uses the Daemons gem. I start it by doing
ruby scripts/outgoing_email_thread.rb start/stop/restart
Basically this thread just loops forever. It wakes up and checks for
stuff to do by asking the database
“Notification.find(:all, :conditions => ‘b_distribute = true’).each do
|n|”
So for me I have a table called Notifications that things get inserted
into by my application. If they want batch mode distribution, they
set b_distribute = true. This thing gets them, does some mojo and
then sends out notifications. Don’t get caught up in my crazy code as
much as the idea of a Daemon thread you start that loops and does your
stuff. My app has about 4 of this bad boys running checking incoming
email, sending email, gathering SMS messages, etc.
#!/usr/bin/env ruby
require ‘rubygems’ # if you use RubyGems
require ‘daemons’
Daemons.run_proc(“outgoing_email_thread”, {:dir_mode => :normal, :dir
=> ‘tmp/pids’} ) do
require “/var/www/yoursite/current/config/environment.rb” # This
has to be a full path to your environment.rb file. scratched my head
here.
loop {
logger.info('outgoing_email_thread: Checking for outgoing email
messages at ’ + Time.now.to_s)
# Find any notifications that need to be distributed
Notification.find(:all, :conditions => 'b_distribute =
true’).each do |n|
begin
n.attach_to_subscribers
rescue Exception => exc
logger.error(“outgoing_email_thread: sending email…” +
exc.message)
logger.error(exc.backtrace.join("\n"))
end
n.update_attributes(:b_distribute => false)
end
# Now notify any users based on Readings
Reading.find(:all, :conditions => 'is_sent = false').each do |r|
begin
r.update_attribute(:is_sent, true)
if r.connector.source.bsd.setting.mail_event &&
r.connector.source.bsd.email_tested
email = NotificationMailer.create_notify(r.connector,
r.notification)
email.set_content_type(“text/html” )
NotificationMailer.deliver(email)
end
rescue Exception => exc
logger.error(“outgoing_email_thread: sending email…” +
exc.message)
logger.error(exc.backtrace.join("\n"))
end
end
EmailMessage.find(:all, :conditions => [‘is_sent = ?’,
false]).each do |email|
email.send_me
end
sleep 13 # My lucky number
}
end
Hope this is helpful.
Mike