我在后台使用带有delayed_job(4.0.6)的ActiveJob,我想找到一个预定的作业来删除它。
例如,如果我有
class MyClass
def my_method
perform_stuff
MyJob.set(wait: 1.month.from_now).perform_later(current_user)
end
end
然后,如果我编辑MyClass实例并再次调用my_method,我想取消该作业并安排一个新作业。
正如本文http://www.sitepoint.com/delayed-jobs-best-practices中所建议的,我在延迟作业表中添加了两列:
table.integer :delayed_reference_id
table.string :delayed_reference_type
add_index :delayed_jobs, [:delayed_reference_id], :name => 'delayed_jobs_delayed_reference_id'
add_index :delayed_jobs, [:delayed_reference_type], :name => 'delayed_jobs_delayed_reference_type'
所以这样我可能会找到延迟的工作并将其销毁。但我想在ActiveJob类中执行此操作,以维护项目中的作业模式。
我想做类似的事情:
class MyJob < ActiveJob::Base
after_enqueue do |job|
user = self.arguments.first
job.delayed_reference_id = user.id,
job.delayed_reference_type = "User"
end
def perform(user)
delete_previous_job_if_exists(user_id)
end
def delete_previous_job_if_exists(user_id)
Delayed::Job.find_by(delayed_reference_id: 1, delayed_reference_type: 'User').delete
end
end
但这不起作用。
有人遇到过这种问题吗?
答案 0 :(得分:2)
两个变化:
1.更新after_enqueue回调,以便您可以更新
delayed_jobs表直接
2.修正了一个拼写错误,其中delayed_reference_id
被硬编码为1
这应该有效:
class MyJob < ActiveJob::Base
after_enqueue do |job|
user = self.arguments.first
delayed_job = Delayed::Job.find(job.provider_job_id)
delayed_job.update(delayed_reference_id:user.id,delayed_reference_type:'User')
end
def perform(user)
delete_previous_job_if_exists(user.id)
end
def delete_previous_job_if_exists(user_id)
Delayed::Job.find_by(delayed_reference_id: user_id, delayed_reference_type: 'User').delete
end
end