延迟::工作序列化你的班级,方法&参数进入处理程序字段。我们目前正在将这种序列化方法硬编码到我们的代码中。这很糟糕。
我们应该如何构建处理程序,以便查找现有的排队作业?
答案 0 :(得分:16)
我这样做:
1)向delayed_jobs
表格
分贝/迁移/ 20110906004963_add_owner_to_delayed_jobs.rb
class AddOwnerToDelayedJobs < ActiveRecord::Migration
def self.up
add_column :delayed_jobs, :owner_type, :string
add_column :delayed_jobs, :owner_id, :integer
add_index :delayed_jobs, [:owner_type, :owner_id]
end
def self.down
remove_column :delayed_jobs, :owner_type
remove_column :delayed_jobs, :owner_id
end
end
2)向Delayed::Job
模型
配置/初始化/ delayed_job.rb
class Delayed::Job < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
attr_accessible :owner, :owner_type, :owner_id
end
3)猴子补丁ActiveRecord::Base
包含职位关联
配置/初始化/ active_record.rb
class ActiveRecord::Base
has_many :jobs, :class_name => "Delayed::Job", :as => :owner
def send_at(time, method, *args)
Delayed::Job.transaction do
job = Delayed::Job.enqueue(Delayed::PerformableMethod.new(self,
method.to_sym, args), 10, time)
job.owner = self
job.save
end
end
def self.jobs
# to address the STI scenario we use base_class.name.
# downside: you have to write extra code to filter STI class specific instance.
Delayed::Job.find_all_by_owner_type(self.base_class.name)
end
end
4)触发工作
class Order < ActiveRecord::Base
after_create :set_reminders
def set_reminders
send_at(2.days.from_now, :send_email_reminder)
end
def send_email_reminder
end
# setting owner for handle_asynchronously notation.
def foo
end
handle_asynchronously :foo, :owner => Proc.new { |o| o }
end
5)检查工作
Order.jobs # lists all the running jobs for Order class
order1.jobs # lists all the running jobs for Order object order1