Search code examples
ruby-on-railsrubyqueueresquejobs

How to find and kill a running Resque job on Rails?


I am using Resque to process some background jobs on a Rails application.

The thing is that clients can cancel this jobs, so:

  • If the job is still on the queue: dequeue it

    Resque.dequeue(GitHub::Jobs::UpdateNetworkGraph, 'repo:135325')
    
  • If the job has finished: do nothing

  • If the job is running: ???

Is there a way to programmatically find the job and in case it is running tell it to stop immediatly? My main concern is to be sure that I kill the desired job, not the current one being processed as it could be a different one form the moment I ask if it is running until the moment I kill it.


Solution

  • I dont think that resque store the process id of the fork process, it does log it though but I dont it store the process id of the child process forked

    you can see over here in Line 139

    With regard to your question of how extract the process id of the running resque job I think the way to do it inside your job itself using redis data-structure

    so consider code below is your perform action for a job create using redis hash(running_process) and add the current process_id in it with the current timestamp

    class MyJob
     @queue = :myjob
    
     def self.perform
       field = Time.now.to_i
       redis.hsetnx "running_process",field,Process.pid 
       ### Rest of the code
    
    
    
       #### when the code is about to finish 
       ##remove the finish process from the 
       redis.hdel "running_process",field
      end
    

    Now you can get the list of all running process by simply querying redis "running_process" hash something like this

    redis.hgetall "running_process"

    Caveats over here If the resque job fail then the process id would never be clean't from

    the hash what ever you do just make sure you cross check the process id you collect

    from the redis hash is actually a running resque job

    Hope this help