ruby-on-rails – 如何找到特定的延迟作业(不是id)?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 如何找到特定的延迟作业(不是id)?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
延迟::工作序列化您的班级,方法和参数进入处理程序字段.我们目前采用硬编码这种序列化方法到我们的代码中.这很糟糕.

我们应该如何构建处理程序,以便查找现有的排队作业?

解决方法

我这样做:

1)向delayed_jobs表添加两个新列

分贝/迁移/ 201109

Order.jobs  # lists all the running jobs for Order class
order1.jobs # lists all the running jobs for Order object order1

963_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_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
原文链接:/ruby/270919.html

猜你在找的Ruby相关文章