为什么perform-method有效,但是没有调用其他delayed_job的事件?

时间:2017-12-01 13:41:07

标签: ruby-on-rails ruby delayed-job

我将delayed_job - gem包含在我的项目中:

# Gemfile
gem 'daemons'
gem 'delayed_job_active_record'

# bash
bundle
rails generate delayed_job:active_record
rake db:migrate

rails g job MyFirstDelayedJob

并编辑app/jobs/my_first_delayed_job_job.rb这样的文件:

class MyFirstDelayedJobJob < ApplicationJob
  queue_as :default

  def perform(*args)
    JOB_LOGGER.info "perform() happened with args: #{args.inspect}"
  end

  def success(job)
    JOB_LOGGER.info "success() happened. Job object: #{job.inspect}"
  end

  def error(job, ex)
    JOB_LOGGER.info "error() happened. Job object: #{job.inspect}, Exception: #{ex.message}"
  end

  def failure(job)
    JOB_LOGGER.info "failure() happened. Job object: #{job.inspect}"
  end
end

从rails控制台启动delayed_job worker以查看调试日志:

Delayed::Worker.new.start

创建了rake任务:

# lib/tasks/run_my_first_delayed_job.rake
desc 'Run job'
task my_first_delayed_job_job: :environment do
  JOB_LOGGER.info 'run_my_first_delayed_job.rake: Starting delayed job...'
  MyFirstDelayedJobJob.set(wait: 30.seconds).perform_later 'arg1', 'arg2', 333
  JOB_LOGGER.info 'run_my_first_delayed_job.rake: Finished.'
end

并在shell中执行:rake my_first_delayed_job_job

执行rake任务后,我有这个日志:

# log/job.log
I, [2017-12-01T19:18:14.591918 #11664]  INFO -- : run_my_first_delayed_job.rake: Starting delayed job...
I, [2017-12-01T19:18:14.655178 #11664]  INFO -- : run_my_first_delayed_job.rake: Finished.
I, [2017-12-01T19:18:44.785494 #11591]  INFO -- : perform() happened with args: ["arg1", "arg2", 333]

为什么未调用successerrorfailure回调?

1 个答案:

答案 0 :(得分:1)

你创建这样的新工作:

MyFirstDelayedJobJob.set(wait: 30.seconds).perform_later 'arg1', 'arg2', 333

您的变体对active-job更正。但是delayed_job gem为运行作业添加了delay方法,因此您需要使用它而不是perform_later。像这样重写你的代码:

# lib/tasks/run_my_first_delayed_job.rake
MyFirstDelayedJobJob.new.delay(run_at: 30.seconds.from_now).perform 'arg1', 'arg2', 333