【问题标题】:Weird exception with delayed_job延迟作业的奇怪异常
【发布时间】:2011-06-08 22:53:00
【问题描述】:

尝试使用延迟作业将作业排队,如下所示:

Delayed::Job.enqueue(BackgroundProcess.new(current_user, object))

current_user 和 object 在我打印出来时不为零。奇怪的是,有时刷新页面或再次运行命令会起作用!

这是异常跟踪:

  Delayed::Backend::ActiveRecord::Job Columns (44.8ms)   SHOW FIELDS FROM `delayed_jobs`

TypeError (wrong argument type nil (expected Data)):
  /Users/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1/yaml.rb:391:in `emit'
  /Users/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1/yaml.rb:391:in `quick_emit'
  /Users/.rvm/rubies/ruby-1.9.1-p378/lib/ruby/1.9.1/yaml/rubytypes.rb:86:in `to_yaml'
  vendor/plugins/delayed_job/lib/delayed/backend/base.rb:65:in `payload_object='
  activerecord (2.3.9) lib/active_record/base.rb:2918:in `block in assign_attributes'
  activerecord (2.3.9) lib/active_record/base.rb:2914:in `each'
  activerecord (2.3.9) lib/active_record/base.rb:2914:in `assign_attributes'
  activerecord (2.3.9) lib/active_record/base.rb:2787:in `attributes='
  activerecord (2.3.9) lib/active_record/base.rb:2477:in `initialize'
  activerecord (2.3.9) lib/active_record/base.rb:725:in `new'
  activerecord (2.3.9) lib/active_record/base.rb:725:in `create'
  vendor/plugins/delayed_job/lib/delayed/backend/base.rb:21:in `enqueue'

【问题讨论】:

    标签: ruby-on-rails delayed-job


    【解决方案1】:

    我猜这是因为您将对象作为参数发送给您的工作(至少我假设 current_user 和 object 实际上是对象而不是 id)。而是发送 id 并在开始执行时开始加载对象。

    例如:

    Delayed::Job.enqueue(BackgroundProcess.new(current_user.id, object.id))
    
    class BackgroundProcess < Struct.new(:user_id, :object_id)
      def perform
        @current_user = User.find(user_id)
        @object = Object.find(object_id)
    
        ...
      end
    end
    

    这样,将 ActiveRecord 序列化到数据库中不会出现任何问题,并且您将始终在作业运行时加载最新的更改。

    【讨论】:

    • 序列化原始对象并不是一件可怕的事情。在工作期间,应该始终拉回一份新副本;但是,如果需要,您可以选择查看之前的记录副本。
    【解决方案2】:

    也遇到了同样的问题。我仍然不知道是什么原因造成的,但由于某种原因克隆对象似乎可以解决它

    u = User.find 123
    u.to_yaml
    => TypeError: wrong argument type nil (expected Data)
    u.clone.to_yaml
    => works like normal
    

    非常令人沮丧。知道根本原因会更好,但如果您绝望,这可能会有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-09-04
      • 1970-01-01
      • 2011-05-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      • 1970-01-01
      • 2019-06-11
      相关资源
      最近更新 更多