Setting up and Using Resque
Gemfile
: add gem 'resque'
, then run bundle install
lib/tasks
, called resque.rake
require 'resque/tasks'
#load the environment when the worker starts up
task "resque:setup" => :environment
bundle exec rake resque:work QUEUE='*'
QUEUE=''
takes in the name of the queue to work on or use *
to load all queuesTo add a job to a queue:
Resque.enqueue(workerClassName, additional_arguments)
in your code@object.id
(can be use to refetch the object without
submitting a complex object that is going to be turned into JSON).Create a new directory within apps
called workers
, for ex: /lib/workers
Create a file (worker) in the workers
directory and name it using the worker_class_name.rb
used in the enqueue
line above.
class WorkerClassName
# 1st requirement
@queue = :name_of_queue #can be named anything
# 2nd requirement
def self.perform(object.id) #takes the additional arguments passed in to enqueue
object = Object.find(abject.id) #refetch the id that was before to complex to send
#through
... #code referencing your API call!
end
end
Complete!
If your worker needs to reference a rake task: Rake::Task['file:name_of_task'].invoke
resque-web
config/routes
: mount Resque::Server, :at => "/resque"
Gemfile
again: gem 'resque', :require => "resque/server"
Devise
:#routes.rb
authenticate :admin do
mount Resque::Server, :at => "/resque"
end
Devise
, an alternative way is to create a new initializer
in
config/initializers
called resque_auth.rb
Resque::Server.use(Rack:;Auth::Basic) do |user, password|
user == "rtrw"
password == "jhtrw"
end
A resque job is any Ruby class or module with a perform class method.
Resque can maintain multiple queues for different job types: by setting the @queue
instance
var, this worker will only look for jobs on the :sleep
queue!
Next, queue the job: Resque.enque(Sleeper, 5)
(in your controller, for example)
{
'class': 'Sleeper',
'args': [5]
}
Jobs should only need access to your models!
When a job is created, it gets appended to a list data structure in Redis.
Rakefile
, add the following: require 'resque/rake'
bundle exec rake -T resque
QUEUE
: controls WHICH queue is monitoredCOUNT
: sets the number of workers (only resque:workers
)bundle exec rake environment resque:work QUEUE=sleep
resque:work
starts a rescue worker (more info run the rake command above)