如何在 Rails 中使用 delay_job 取消预定作业? [英] How to cancel scheduled job with delayed_job in Rails?

查看:31
本文介绍了如何在 Rails 中使用 delay_job 取消预定作业?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在安排一个作业运行,比如说,10 分钟.如何在不使用模型中任何类型的脏额外字段的情况下正确取消此特定作业等.是否有任何要求删除特定作业或与特定模型、实例等相关的作业?

I am scheduling a job to run in say, 10 minutes. How to properly cancel this particular job without using any kind of dirty extra fields in model and so on. Is there any call to remove particular job, or jobs related to specific model, instance, etc?

推荐答案

disclaimer: 我不是delayed_job的专家用户...

disclaimer: I am not an expert user of delayed_job...

"是否有任何要求删除特定作业或与特定模型、实例等相关的作业?"

Delayed::Job 只是一个 ActiveRecord 对象,因此您可以查找和销毁任何这些记录.根据您的用例,这可以用不同的方式处理.如果有人要手动销毁它们,这可以通过您的 Web 应用程序中的管理界面来处理.

Delayed::Job is just an ActiveRecord object so you can find and destroy any of those records. Depending on your use case this could be handled different ways. If someone is going to manually destroy them this could be handled through an admin interface in your web app.

# list all jobs
Delayed::Job.all
# find a job by id
job = Delayed::Job.find(params[:id])
# delete it
job.delete

如果您需要按作业类型"删除一些进程外任务,您可以遍历每个作业,如果与您的作业匹配,则将其删除;在脚本/控制台中试试这个

if you need some out of process task deleting jobs by 'job type' you could loop through each one and delete it if it matches your job; try this in script/console

class MyJob < Struct.new(:some_value);
    def perform
        # ...
    end
end

my_job = MyJob.new('xyz')
job = Delayed::Job.enqueue(my_job, 0, 1.hour.from_now)
job.name
# => "MyJob"
job.handler
# => "--- !ruby/struct:MyJob 
some_value: xyz
"

因此,如果您想删除 MyJob 类型的所有作业

so given the above if you wanted to delete all jobs of type MyJob

Delayed::Job.all.each do |job|
    if job.name == "MyJob" then
        job.delete
    end
end

这对您的情况可能有帮助,也可能无济于事?在许多情况下,您可能想要删除 MyJob,但仅限于 :some_value 属性是abc"而不是xyz"的地方.在这种情况下,您可能需要在 MyJob 对象上实现display_name".如果存在,job.name 将使用它

this may or may not help for your situation? in many cases you might want to delete a MyJob but only where the :some_value attribute was 'abc' and not 'xyz'. In this case you might need to implement a 'display_name' on your MyJob object. job.name will use this if it exists

class MyJob < Struct.new(:user_id);
    def perform
        # ...
    end

    def display_name
        return "MyJob-User-#{user_id}"
    end 
end

# store reference to a User
my_job = MyJob.new(User.first.id) # users.id is 1
job = Delayed::Job.enqueue(my_job, 0, 1.hour.from_now)
job.name
# => "MyJob-User-1"
job.handler
# => "--- !ruby/struct:MyJob 
user_id: 1
"

这样您就可以更有选择性地删除哪些记录?

this way you could be more selective about which records to delete?

希望这能为您提供有关处理它的可能方法的足够信息吗?

hopefully this gives you enough information on possible ways to handle it?

这篇关于如何在 Rails 中使用 delay_job 取消预定作业?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆