You are here: Browse Railsplugins Background Fu
Background tasks made dead simple.
There are bonus features available if you set ActiveRecord::Base.allow_concurrency = true in your environment.
These features are: * monitoring progress (perfect for ajax progress bars) * stopping a running worker in a merciful way.
Read the code (short and easy) to discover them.
./script/plugin install https://svn.trix.pl/public/background_fu/
ruby ./script/generate background rake db:migrate ruby ./script/daemons start
then try in console:
job_id = Job.enqueue!(ExampleWorker, :add, 1, 2).id
... and after few seconds when background daemon completes the job …
Job.find(job_id).result should equal 3
In lib/workers/example_worker.rb:
def add(a, b) a + b end
end
In lib/workers/example_monitored_worker.rb:
include BackgroundFu::WorkerMonitoring
def long_and_monitored my_progress = 0 end
record_progress(my_progress)
while(my_progress < 100)
my_progress += 1
record_progress(my_progress)
sleep 1
end
record_progress(100)end
In a controller:
def create
session[:job_id] = Job.enqueue!(ExampleWorker, :add, 1, 2).id
# or try the monitored worker: session[:job_id] = Job.enqueue!(ExampleMonitoredWorker, :long_and_monitored)
end
def show
@job = Job.find(session[:job_id])
@result = @job.result if @job.finished?
# or check progress if your worker is monitored: @progress = @job.progress
end
def index
@jobs = Job.find(:all)
end
def destroy
Job.find(session[:job_id]).destroy
end
Handy Capistrano tasks:
namespace :deploy do
desc "Run this after every successful deployment"
task :after_default do
restart_background_fu
end
end
desc “Restart BackgroundFu daemon” task :restart_background_fu do run “RAILS_ENV=production ruby #{current_path}/script/daemons stop” run “RAILS_ENV=production ruby #{current_path}/script/daemons start” end
Enjoy!
Copyright© 2007 Jacek Becela, released under the MIT license
Homepage: https://svn.trix.pl/public/background_fu