ActiveJob

Mikhail Chuprysnki edited this page Jun 8, 2016 · 6 revisions

Rails 4.2 introduced ActiveJob, a standard interface for job runners. Here is how to use Resque with ActiveJob.

  • Make sure you have Redis installed and gem 'resque' is in your Gemfile

  • Set Resque as queue adapter in config/application.rb.

config.active_job.queue_adapter = :resque

  • In your Rakefile add the following to access resque rake tasks

require 'resque/tasks'

  • Generate your job

rails g job Cleanup

  • This will generate new job at app/jobs folder:
class CleanupJob < ActiveJob::Base
  queue_as :default

  def perform(arg1, arg2)
    #your long running code here
  end
end
  • Run this job anywhere at your code like this:
#just run
CleanupJob.perform_later(arg1, arg2)

#or set the queue name
CleanupJob.set(queue: user.name).perform_later(arg1, arg2)

#or set the delay
CleanupJob.set(wait: 1.week).perform_later(arg1, arg2)

#or run immediately
CleanupJob.perform_now(arg1, arg2)
  • Run Redis server
redis-server /usr/local/etc/redis.conf
  • Run the following in console (otherwise your workers will not start (just pending))
QUEUE=* rake resque:work
  • Additionally, you can mount web-version of Resque to your project, add this to your routes.rb
require 'resque/server'
mount Resque::Server, at: '/jobs'

#or if you would like to protect this with Devise
devise_for :users

authenticate :user do
  mount Resque::Server, at: '/jobs'
end