如何在Rails中使用delay_job取消计划的工作? [英] How to cancel scheduled job with delayed_job in Rails?

查看:79
本文介绍了如何在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: 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 \nsome_value: xyz\n"

如果您要删除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 \nuser_id: 1\n"

您可能对删除哪些记录有更多选择?

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天全站免登陆