fangtingting
12/17/2017 - 8:12 AM

Active Job代码示例

Active Job

# rails generate job guests_cleanup
# 可以创建运行在一个特定队列上的任务
# rails g job guests_cleanup --queue urgent

# Active Job 是用来声明任务,并把任务放到多种多样的队列后台中执行的框架。
# 从定期地安排清理,费用账单到发送邮件,任何事情都可以是任务。
# 任何可以切分为小的单元和并行执行的任务都可以用 Active Job 来执行。
class GuestsCleanupJob < ActiveJob::Base
  queue_as :default
  #捕获异常
  rescue_from(ActiveRecord::RecordNotFound) do |exception|
   # do something with the exception
  end
  def perform(*args)
    # Do something later
  end

end

# 将加入到队列系统中任务立即执行
GuestsCleanupJob.perform_later record
# 在明天中午执行加入队列的任务
GuestsCleanupJob.set(wait_until: Date.tomorrow.noon).perform_later(record)
# 一星期后执行加入到队列的任务
GuestsCleanupJob.set(wait: 1.week).perform_later(record)

# 如果没有设置连接器,任务会立即执行。Active Job 内建支持多种队列后台连接器(Sidekiq、Resque、Delayed Job 等)。
#在config/application.rb里配置
require "active_job/railtie"
module YourApp
  class Application < Rails::Application
    # 设置队里后台
config.active_job.queue_adapter = :sidekiq
#设置所有任务的队列名称的前缀
config.active_job.queue_name_prefix=Rails.env
#设置队列名之间的分隔符
config.active_job.queue_name_delimiter = '.'
  end
end


# 任务回调
# before_enqueue、around_enqueue、after_enqueue、before_perform、around_perform、after_perform。
class GuestsCleanupJob < ActiveJob::Base
  queue_as :default
  before_enqueue do |job|
    # do something with the job instance
  end 
  around_perform do |job, block|
    # do something before perform
    block.call
    # do something after perform
  end
  def perform
    # Do something later
  end
end


#Action Mailer任务:现代网站应用中最常见的任务之一是,在请求响应周期外发送 Email,这样所有用户不需要焦急地等待邮件的发送。
# Active Job 集成到 Action Mailer 里了,所以能够简单的实现异步发送邮件。
# If you want to send the email now use #deliver_now
UserMailer.welcome(@user).deliver_now
 
# If you want to send the email through Active Job use #deliver_later
UserMailer.welcome(@user).deliver_later