我有一个Rails应用程序,我在其中使用delayed_job。我想检测一下我是否处于delayed_job进程中;
之类的东西if in_delayed_job?
# do something only if it is a delayed_job process...
else
# do something only if it is not a delayed_job process...
end
但我无法弄清楚如何。这就是我现在正在使用的:
IN_DELAYED_JOB = begin
basename = File.basename $0
arguments = $*
rake_args_regex = /\Ajobs:/
( basename == 'delayed_job' ) ||
( basename == 'rake' && arguments.find{ |v| v =~ rake_args_regex } )
end
另一种解决方案是,正如@MrDanA所说:
$ DELAYED_JOB=true script/delayed_job start
# And in the app:
IN_DELAYED_JOB = ENV['DELAYED_JOB'].present?
但他们是恕我直言的弱解决方案。任何人都可以提出更好的解决方案吗?
答案 0 :(得分:1)
我处理这些的方式是通过一个偏执狂工人。我使用delayed_job进行上传到我网站的视频转码。在视频模型中,我有一个名为video_processing的字段,默认设置为0 / null。每当视频被delayed_job转码(无论是创建还是更新视频文件),它都将使用delayed_job中的钩子,并在作业开始时更新video_processing。作业完成后,完成的挂钩会将该字段更新为0。
在我的视图/控制器中,我可以video.video_processing? ? "Video Transcoding in Progress" : "Video Fished Transcoding"
答案 1 :(得分:1)
也许是这样的。在您的类中添加一个字段,并在调用从延迟作业完成所有工作的方法时进行设置:
class User < ActiveRecord::Base
attr_accessor :in_delayed_job
def queue_calculation_request
Delayed::Job.enqueue(CalculationRequest.new(self.id))
end
def do_the_work
if (in_delayed_job)
puts "Im in delayed job"
else
puts "I was called directly"
end
end
class CalculationRequest < Struct.new(:id)
def perform
user = User.find(id)
user.in_delayed_job = true
user.do_the_work
end
def display_name
"Perform the needeful user Calculations"
end
end
end
以下是它的外观:
来自延迟工作:
Worker(host:Johns-MacBook-Pro.local pid:67020)] Starting job worker
Im in delayed job
[Worker(host:Johns-MacBook-Pro.local pid:67020)] Perform the needeful user Calculations completed after 0.2787
[Worker(host:Johns-MacBook-Pro.local pid:67020)] 1 jobs processed at 1.5578 j/s, 0 failed ...
从控制台
user = User.first.do_the_work
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1 [["id", 101]]
I was called directly
答案 2 :(得分:1)
这对我有用:
def delayed_job_worker?
(ENV["_"].include? "delayed_job")
end
Unix会将“_”环境变量设置为当前命令。
如果你有一个名为“not_a_delayed_job”的bin脚本,那就错了,但不要这样做。
答案 3 :(得分:0)
ENV ['PROC_TYPE']如何左右 只说到heroku ...但是当你是一个工人dyno时,这将被设置为'worker' 我用它作为“我在DJ中”
答案 4 :(得分:0)
您可以为延迟的工作创建插件,例如在is_dj_job_plugin.rb
目录中创建文件config/initializers
。
class IsDjJobPlugin < Delayed::Plugin
callbacks do |lifecycle|
lifecycle.around(:invoke_job) do |job, *args, &block|
begin
old_is_dj_job = Thread.current[:is_dj_job]
Thread.current[:is_dj_job] = true
block.call(job, *args) # Forward the call to the next callback in the callback chain
Thread.current[:is_dj_job] = old_is_dj_job
end
end
end
def self.is_dj_job?
Thread.current[:is_dj_job] == true
end
end
Delayed::Worker.plugins << IsDjJobPlugin
然后您可以通过以下方式进行测试:
class PrintDelayedStatus
def run
puts IsDjJobPlugin.is_dj_job? ? 'delayed' : 'not delayed'
end
end
PrintDelayedStatus.new.run
PrintDelayedStatus.new.delay.run