7

delayd_jobを使用するRailsアプリがあります。delay_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?

しかし、それらは私見の弱い解決策です。誰かがより良い解決策を提案できますか?

4

5 に答える 5

1

私がこれらを処理する方法は、パラノイド ワーカーを使用することです。自分のサイトにアップロードされたビデオのトランスコーディングには、delayed_job を使用しています。ビデオのモデル内に、デフォルトで 0/null に設定されている video_processing というフィールドがあります。ビデオがdelayed_jobによってトランスコードされているときはいつでも(ビデオファイルの作成時または更新時)、delayed_jobからのフックを使用し、ジョブが開始するたびにvideo_processingを更新します。ジョブが完了すると、完了したフックがフィールドを 0 に更新します。

私のビュー/コントローラーでできることvideo.video_processing? ? "Video Transcoding in Progress" : "Video Fished Transcoding"

于 2013-02-13T17:51:14.643 に答える
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
于 2013-02-13T18:44:31.307 に答える
1

これは私のために働く:

def delayed_job_worker?
  (ENV["_"].include? "delayed_job")
end

Unix は「_」環境変数を現在のコマンドに設定します。

「not_a_delayed_job」という bin スクリプトがあるとまずいですが、そうしないでください。

于 2016-10-31T21:55:40.323 に答える