实现Email队列

阅读更多
Rails部署环境下使用lighttpd进程实时发送email比较耗时间,对于要求不太紧急的email,可以暂存在Email队列里,利用linux的crontab定时读取发送

1,加一张表email_queue:
class CreateEmailQueues < ActiveRecord::Migration
  def self.up
    create_table :email_queues do |t|
      t.string :subject
      t.text :content
      t.string :recipient
      t.timestamps
    end
  end

  def self.down
    drop_table :email_queues
  end
end

需要发送Email时就向该表插数据即可

2,EmailQueue
class EmailQueue < ActiveRecord::Base
  def self.send_all_email_in_queue
    EmailQueue.find(:all, :order => "created_at asc").each do |email|
      ExceptionNotifier.deliver_sys_email(email.recipient, email.subject, email.content)
      email.destroy
    end
  end
end


3,写一个send_sys_email_job.rb文件
ENV['RAILS_ENV'] = 'production'
require File.dirname(__FILE__)+'/config/environment'
EmailQueue.send_all_email_in_queue


4,写一个send_sys_email.sh文件
#!/bin/bash
S=`ps aux|grep send_sys_email_job|grep -v grep`
if ["$RS" = ""]; then
  echo "No send_sys_email instance, start a new one!"
  /usr/bin/ruby /var/www/vhosts/hideto/html/www.beyondrails.com/send_sys_email_job.rb
else
  echo "Already exists a send_sys_email_job instance, exit!"
  exit
fi

这里有陷阱,调用send_sys_email_job.rb文件时必须写全绝对路径,因为crontab里没有环境变量

5,crontab -e
*/10 * * * * /var/www/vhosts/hideto/html/www.beyondrails.com/send_sys_email.sh


这样就会每间隔10分钟检查一遍Email队列里有没有邮件并发送

你可能感兴趣的:(Rails,lighttpd,Linux,ActiveRecord,Ruby)