SlideShare a Scribd company logo
Background
                           Processing
                                    Rob Mack
                           Austin on Rails - April 2009




Thursday, April 30, 2009
Why Background
                            Processing?



Thursday, April 30, 2009
Simple Background
                         Processing



Thursday, April 30, 2009
script/runner

              From RAILS_ROOT:


                      • script/runner lib/do_work.rb
                      • script/runner ‘Worker.do_work’




Thursday, April 30, 2009
Rake
                   def call_rake(task,options={})
                       options[:rails_env] = RAILS_ENV
                       args = options.map{|n,v| quot;#{n.to_s.upcase}='#{v}'quot;}
                       system quot;rake #{task} #{args.join(' ')} "
                    end




                           • Episode #127 Railscasts




Thursday, April 30, 2009
Daemons


                           http://daemons.rubyforge.org/




             http://github.com/dougal/daemon_generator/




Thursday, April 30, 2009
Generate A Daemon

                           • script/generate daemon my_worker


                            create   lib/daemons
                            create   script/daemons
                            create   lib/daemons/my_worker.rb
                            create   lib/daemons/my_worker_ctl
                            create   config/daemons.yml



Thursday, April 30, 2009
Do Some Work

                              $running = true
                              Signal.trap(quot;TERMquot;) do
                                $running = false
                              end

                              while($running) do
                                # Do some work
                                sleep 10
                              end




                           lib/daemons/my_worker.rb


Thursday, April 30, 2009
Kick It Off


                           lib/daemons/my_worker_ctl start
                           lib/daemons/my_worker_ctl stop




Thursday, April 30, 2009
Spawn



                           http://github/tra/spawn




Thursday, April 30, 2009
Spawn - Do Some Work

                             def my_action
                               flash[:notice] = quot;Processing ... quot;
                               spawn do
                                 # do some processing
                               end
                             end




Thursday, April 30, 2009
Simple Queues



Thursday, April 30, 2009
ar_mailer

                           setup:

                             gem install ar_mailer
                             ar_sendmail --create-migration
                             ar_sendmail --create-model


                           http://seattlerb.rubyforge.org/ar_mailer/


Thursday, April 30, 2009
ar_mailer Schema

                           create_table   quot;emailsquot; do |t|
                             t.string     quot;fromquot;
                             t.string     quot;toquot;
                             t.integer    quot;last_send_attemptquot;, :default => 0
                             t.text       quot;mailquot;,              :limit => 16777215
                             t.datetime   quot;created_onquot;
                           end




Thursday, April 30, 2009
ar_mailer Setup
                environment.rb
                config.gem 'ar_mailer', :version => '1.3.1',
                   :lib => 'action_mailer/ar_mailer'

                config.action_mailer.delivery_method = :activerecord




                  Mail Model:
                   class MyMailer < ActionMailer::ARMailer




Thursday, April 30, 2009
Mail Something



                           MyMailer.deliver_newsletter @recipients




Thursday, April 30, 2009
The Worker Process



                      ar_sendmail --daemonize --max-age 0




Thursday, April 30, 2009
BackgrounDRb


                         http://backgroundrb.rubyforge.org
                     http://github.com/gnufied/backgroundrb




Thursday, April 30, 2009
BackgrounDRb Setup
                      • sudo gem install chronic packet
                      • script/plugin install git://github.com/
                        gnufied/backgroundrb.git
                      • rake backgroundrb:setup
                      • rake db:migrate
                      • edit config/backgroundrb.yml
                      • script/generate worker my_worker

Thursday, April 30, 2009
BackgrounDRb Schema
                           create_table   quot;bdrb_job_queuesquot; do |t|
                             t.text       quot;argsquot;
                             t.string     quot;worker_namequot;
                             t.string     quot;worker_methodquot;
                             t.string     quot;job_keyquot;
                             t.integer    quot;takenquot;
                             t.integer    quot;finishedquot;
                             t.integer    quot;timeoutquot;
                             t.integer    quot;priorityquot;
                             t.datetime   quot;submitted_atquot;
                             t.datetime   quot;started_atquot;
                             t.datetime   quot;finished_atquot;
                             t.datetime   quot;archived_atquot;
                             t.string     quot;tagquot;
                             t.string     quot;submitter_infoquot;
                             t.string     quot;runner_infoquot;
                             t.string     quot;worker_keyquot;
                             t.datetime   quot;scheduled_atquot;
                           end




Thursday, April 30, 2009
Do Some Work
            class MyWorker < BackgrounDRb::MetaWorker
              set_worker_name :my_worker
              def create(args = nil)
                # initialization goes here
              end

              def do_work(user_id = nil)
                # do some work
              end
            end

            def my_action
              flash[:notice] = quot;Processing ...quot;
              MiddleMan.worker(:my_worker).async_do_work(:arg => @user.id)
            end


Thursday, April 30, 2009
Persistent Work


           def my_action
             MiddleMan(:my_worker).enq_do_work(:job_key => quot;unique_keyquot;)
           end




Thursday, April 30, 2009
Poll Status

                           class MyWorker < BackgrounDRb::MetaWorker

                             set_worker_name :my_worker

                             def create(args = nil)
                               # initialization goes here
                             end

                             def do_work(user_id = nil)
                               # do some work
                               register_status quot;almost donequot;
                             end
                           end




Thursday, April 30, 2009
Poll Status

                    def my_action
                      @job_key = MiddleMan.new_worker(
                        :worker => :my_worker,
                        :job_key => quot;unique_keyquot;
                      )
                      MiddleMan.worker(:my_worker, @job_key).
                            do_work(@user.id)
                    end

                    def check_status
                      @status = MiddleMan.worker(:my_worker, @job_key).
                            ask_status
                    end




Thursday, April 30, 2009
The Worker Process



                             script/backgroundrb start




Thursday, April 30, 2009
BJ - Background Job



                    http://codeforpeople.rubyforge.org/svn/bj




Thursday, April 30, 2009
Bj - Setup
                   script/plugin install http://
         codeforpeople.rubyforge.org/svn/rails/plugins/bj
                          script/bj setup


                           gem install bj
                            require ‘bj’
                              bj setup



Thursday, April 30, 2009
Bj Schema
                           create_table   quot;bj_jobquot;, :primary_key => quot;bj_job_idquot; do |t|
                             t.text       quot;commandquot;
                             t.text       quot;statequot;
                             t.integer    quot;priorityquot;
                             t.text       quot;tagquot;
                             t.integer    quot;is_restartablequot;
                             t.text       quot;submitterquot;
                             t.text       quot;runnerquot;
                             t.integer    quot;pidquot;
                             t.datetime   quot;submitted_atquot;
                             t.datetime   quot;started_atquot;
                             t.datetime   quot;finished_atquot;
                             t.text       quot;envquot;
                             t.text       quot;stdinquot;
                             t.text       quot;stdoutquot;
                             t.text       quot;stderrquot;
                             t.integer    quot;exit_statusquot;
                           end




Thursday, April 30, 2009
Bj Schema
                   create_table   quot;bj_job_archivequot;, :primary_key => quot;bj_job_archive_idquot; do |t|
                     t.text       quot;commandquot;
                     t.text       quot;statequot;
                     t.integer    quot;priorityquot;
                     t.text       quot;tagquot;
                     t.integer    quot;is_restartablequot;
                     t.text       quot;submitterquot;
                     t.text       quot;runnerquot;
                     t.integer    quot;pidquot;
                     t.datetime   quot;submitted_atquot;
                     t.datetime   quot;started_atquot;
                     t.datetime   quot;finished_atquot;
                     t.datetime   quot;archived_atquot;
                     t.text       quot;envquot;
                     t.text       quot;stdinquot;
                     t.text       quot;stdoutquot;
                     t.text       quot;stderrquot;
                     t.integer    quot;exit_statusquot;
                   end




Thursday, April 30, 2009
Do Some Work

                           def my_action
                             flash[:notice] = quot;Processing ...quot;
                             Bj.submit './script/runner /lib/do_some_work.rb'
                           end




                           def my_other_action
                             flash[:notice] = quot;Processing ...quot;
                             Bj.submit 'echo foobar', :tag => 'sample job'
                           end




Thursday, April 30, 2009
The Worker Process



                           bj run --forever --rails_env=development




Thursday, April 30, 2009
Delayed Job



                           http://github.com/tobi/delayed_job/




Thursday, April 30, 2009
Delayed Job Setup



                      • script/plugin install git://github.com/
                        tobi/delayed_job.git
                      • create a delayed jobs table




Thursday, April 30, 2009
Delayed Job Schema

                            create_table   quot;delayed_jobsquot; do |t|
                              t.integer    quot;priorityquot;,   :default => 0
                              t.integer    quot;attemptsquot;,   :default => 0
                              t.text       quot;handlerquot;
                              t.string     quot;last_errorquot;
                              t.datetime   quot;run_atquot;
                              t.datetime   quot;locked_atquot;
                              t.datetime   quot;failed_atquot;
                              t.string     quot;locked_byquot;
                              t.datetime   quot;created_atquot;
                              t.datetime   quot;updated_atquot;
                            end




Thursday, April 30, 2009
Do Some Work

                            class MyWorker

                              attr_accessor :user_id

                              def initialize(user)
                                self.user_id = user_id
                              end

                              def perform
                                User.find user_id
                                # do some work
                              end
                            end




Thursday, April 30, 2009
Do Some Work

             def my_action
               flash[:notice] = quot;Processing ...quot;
               Delayed::Job.enqueue MyWorker.new(@user.id)
             end




              def my_action
                flash[:notice] = quot;Processing ...quot;
                MyMailer.new(@user.id).send_later(:deliver_newsletter)
              end



Thursday, April 30, 2009
The Worker Process



                                rake jobs:work




Thursday, April 30, 2009
Workling



                   http://github.com/purzelrakete/workling/




Thursday, April 30, 2009
Workling Install


     script/plugin install git://github.com/purzelrakete/
                           workling.git




Thursday, April 30, 2009
Do Some Work
                           class MyWorker < Workling::Base
                             def do_something(options)
                               # do some work
                             end
                           end




                           def my_action
                             flash[:notice] = quot;Processing ...quot;
                             MyWorker.async_do_something :user_id => @user.id
                           end




Thursday, April 30, 2009
The Worker Process

                             with spawn:
                             script/workling_client start


                             with starling:
                             sudo starling -d
                             script/workling_client start


Thursday, April 30, 2009
Starling



                           http://github.com/starling/starling/




Thursday, April 30, 2009
Even More Options

             • Background Fu - http://github.com/ncr/
               background-fu
             • Roofus Scheduler - http://github.com/
               jmettraux/rufus-scheduler
             • AP4R - http://rubyforge.org/projects/
               ap4r/



Thursday, April 30, 2009
Advanced Queues



Thursday, April 30, 2009
Kestrel



                           http://github.com/robey/kestrel/




Thursday, April 30, 2009
Rabbit MQ



                           http://www.rabbitmq.com/




Thursday, April 30, 2009
Active MQ



                           http://activemq.apache.org/




Thursday, April 30, 2009
Amazon SQS



                           http://aws.amazon.com/sqs/




Thursday, April 30, 2009
Monitoring


                      • god - http://github.com/mojombo/
                        god/
                      • launchd - OS X
                      • monit - http://mmonit.com/monit/



Thursday, April 30, 2009
Persistant?
                                                                 Yes
                                 No
                                                                             Scaling concerns or fear
         I enjoy
                                                                                 of commitment?
       managing a
        process?
                                                                             No              Yes
                            No
             Yes
                                                             Delayed Job
                                                            Background Job
                                      Spawn                                                        Workling
      Daemons



                                                     Are you the                          Kestrel
                 Starling        Probably Not                            Yes
                                                     next Twitter?                       Rabbit MQ




Thursday, April 30, 2009
Thanks


                            rob@robmack.com

                           twitter.com/robmack




Thursday, April 30, 2009

More Related Content

Similar to Background Processing in Ruby on Rails

Disconnecting the Database with ActiveRecord
Disconnecting the Database with ActiveRecordDisconnecting the Database with ActiveRecord
Disconnecting the Database with ActiveRecord
Ben Mabey
 
Outside In Development With Cucumber
Outside In Development With CucumberOutside In Development With Cucumber
Outside In Development With CucumberLittleBIGRuby
 
Outside-In Development With Cucumber
Outside-In Development With CucumberOutside-In Development With Cucumber
Outside-In Development With Cucumber
Ben Mabey
 
ruby test-all parallel running
ruby test-all parallel runningruby test-all parallel running
ruby test-all parallel running
Shota Fukumori
 
Ruby Isn't Just About Rails
Ruby Isn't Just About RailsRuby Isn't Just About Rails
Ruby Isn't Just About Rails
Adam Wiggins
 
Page Caching Resurrected: A Fairy Tale
Page Caching Resurrected: A Fairy TalePage Caching Resurrected: A Fairy Tale
Page Caching Resurrected: A Fairy Tale
Ben Scofield
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de Rails
Fabio Akita
 
Ruby On Rails Presentation Barcamp Antwerp.Key
Ruby On Rails Presentation Barcamp Antwerp.KeyRuby On Rails Presentation Barcamp Antwerp.Key
Ruby On Rails Presentation Barcamp Antwerp.KeyBert Goethals
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
noelrap
 
Automated Testing with Ruby
Automated Testing with RubyAutomated Testing with Ruby
Automated Testing with Ruby
Keith Pitty
 
Ruby & Machine Vision - Talk at Sheffield Hallam University Feb 2009
Ruby & Machine Vision - Talk at Sheffield Hallam University Feb 2009Ruby & Machine Vision - Talk at Sheffield Hallam University Feb 2009
Ruby & Machine Vision - Talk at Sheffield Hallam University Feb 2009
Jan Wedekind
 
Django Testing
Django TestingDjango Testing
Django Testing
ericholscher
 
A Toda Maquina Con Ruby on Rails
A Toda Maquina Con Ruby on RailsA Toda Maquina Con Ruby on Rails
A Toda Maquina Con Ruby on Rails
Rafael García
 
Your own (little) gem: building an online business with Ruby
Your own (little) gem: building an online business with RubyYour own (little) gem: building an online business with Ruby
Your own (little) gem: building an online business with RubyLindsay Holmwood
 
MacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meetMacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meet
Matt Aimonetti
 
Fixture Replacement Plugins
Fixture Replacement PluginsFixture Replacement Plugins
Fixture Replacement PluginsPaul Klipp
 
Sinatra
SinatraSinatra
Debugging and Error handling
Debugging and Error handlingDebugging and Error handling
Debugging and Error handlingSuite Solutions
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
Thaichor Seng
 

Similar to Background Processing in Ruby on Rails (20)

Disconnecting the Database with ActiveRecord
Disconnecting the Database with ActiveRecordDisconnecting the Database with ActiveRecord
Disconnecting the Database with ActiveRecord
 
Outside In Development With Cucumber
Outside In Development With CucumberOutside In Development With Cucumber
Outside In Development With Cucumber
 
Outside-In Development With Cucumber
Outside-In Development With CucumberOutside-In Development With Cucumber
Outside-In Development With Cucumber
 
ruby test-all parallel running
ruby test-all parallel runningruby test-all parallel running
ruby test-all parallel running
 
Ruby Isn't Just About Rails
Ruby Isn't Just About RailsRuby Isn't Just About Rails
Ruby Isn't Just About Rails
 
Page Caching Resurrected: A Fairy Tale
Page Caching Resurrected: A Fairy TalePage Caching Resurrected: A Fairy Tale
Page Caching Resurrected: A Fairy Tale
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de Rails
 
Ruby On Rails Presentation Barcamp Antwerp.Key
Ruby On Rails Presentation Barcamp Antwerp.KeyRuby On Rails Presentation Barcamp Antwerp.Key
Ruby On Rails Presentation Barcamp Antwerp.Key
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Automated Testing with Ruby
Automated Testing with RubyAutomated Testing with Ruby
Automated Testing with Ruby
 
Ruby & Machine Vision - Talk at Sheffield Hallam University Feb 2009
Ruby & Machine Vision - Talk at Sheffield Hallam University Feb 2009Ruby & Machine Vision - Talk at Sheffield Hallam University Feb 2009
Ruby & Machine Vision - Talk at Sheffield Hallam University Feb 2009
 
Django Testing
Django TestingDjango Testing
Django Testing
 
A Toda Maquina Con Ruby on Rails
A Toda Maquina Con Ruby on RailsA Toda Maquina Con Ruby on Rails
A Toda Maquina Con Ruby on Rails
 
Your own (little) gem: building an online business with Ruby
Your own (little) gem: building an online business with RubyYour own (little) gem: building an online business with Ruby
Your own (little) gem: building an online business with Ruby
 
MacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meetMacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meet
 
Fixture Replacement Plugins
Fixture Replacement PluginsFixture Replacement Plugins
Fixture Replacement Plugins
 
Um2010
Um2010Um2010
Um2010
 
Sinatra
SinatraSinatra
Sinatra
 
Debugging and Error handling
Debugging and Error handlingDebugging and Error handling
Debugging and Error handling
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby Metaprogramming
 

Recently uploaded

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
Globus
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
Peter Spielvogel
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 

Recently uploaded (20)

PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfSAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdf
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 

Background Processing in Ruby on Rails

  • 1. Background Processing Rob Mack Austin on Rails - April 2009 Thursday, April 30, 2009
  • 2. Why Background Processing? Thursday, April 30, 2009
  • 3. Simple Background Processing Thursday, April 30, 2009
  • 4. script/runner From RAILS_ROOT: • script/runner lib/do_work.rb • script/runner ‘Worker.do_work’ Thursday, April 30, 2009
  • 5. Rake def call_rake(task,options={}) options[:rails_env] = RAILS_ENV args = options.map{|n,v| quot;#{n.to_s.upcase}='#{v}'quot;} system quot;rake #{task} #{args.join(' ')} &quot; end • Episode #127 Railscasts Thursday, April 30, 2009
  • 6. Daemons http://daemons.rubyforge.org/ http://github.com/dougal/daemon_generator/ Thursday, April 30, 2009
  • 7. Generate A Daemon • script/generate daemon my_worker create lib/daemons create script/daemons create lib/daemons/my_worker.rb create lib/daemons/my_worker_ctl create config/daemons.yml Thursday, April 30, 2009
  • 8. Do Some Work $running = true Signal.trap(quot;TERMquot;) do $running = false end while($running) do # Do some work sleep 10 end lib/daemons/my_worker.rb Thursday, April 30, 2009
  • 9. Kick It Off lib/daemons/my_worker_ctl start lib/daemons/my_worker_ctl stop Thursday, April 30, 2009
  • 10. Spawn http://github/tra/spawn Thursday, April 30, 2009
  • 11. Spawn - Do Some Work def my_action flash[:notice] = quot;Processing ... quot; spawn do # do some processing end end Thursday, April 30, 2009
  • 13. ar_mailer setup: gem install ar_mailer ar_sendmail --create-migration ar_sendmail --create-model http://seattlerb.rubyforge.org/ar_mailer/ Thursday, April 30, 2009
  • 14. ar_mailer Schema create_table quot;emailsquot; do |t| t.string quot;fromquot; t.string quot;toquot; t.integer quot;last_send_attemptquot;, :default => 0 t.text quot;mailquot;, :limit => 16777215 t.datetime quot;created_onquot; end Thursday, April 30, 2009
  • 15. ar_mailer Setup environment.rb config.gem 'ar_mailer', :version => '1.3.1', :lib => 'action_mailer/ar_mailer' config.action_mailer.delivery_method = :activerecord Mail Model: class MyMailer < ActionMailer::ARMailer Thursday, April 30, 2009
  • 16. Mail Something MyMailer.deliver_newsletter @recipients Thursday, April 30, 2009
  • 17. The Worker Process ar_sendmail --daemonize --max-age 0 Thursday, April 30, 2009
  • 18. BackgrounDRb http://backgroundrb.rubyforge.org http://github.com/gnufied/backgroundrb Thursday, April 30, 2009
  • 19. BackgrounDRb Setup • sudo gem install chronic packet • script/plugin install git://github.com/ gnufied/backgroundrb.git • rake backgroundrb:setup • rake db:migrate • edit config/backgroundrb.yml • script/generate worker my_worker Thursday, April 30, 2009
  • 20. BackgrounDRb Schema create_table quot;bdrb_job_queuesquot; do |t| t.text quot;argsquot; t.string quot;worker_namequot; t.string quot;worker_methodquot; t.string quot;job_keyquot; t.integer quot;takenquot; t.integer quot;finishedquot; t.integer quot;timeoutquot; t.integer quot;priorityquot; t.datetime quot;submitted_atquot; t.datetime quot;started_atquot; t.datetime quot;finished_atquot; t.datetime quot;archived_atquot; t.string quot;tagquot; t.string quot;submitter_infoquot; t.string quot;runner_infoquot; t.string quot;worker_keyquot; t.datetime quot;scheduled_atquot; end Thursday, April 30, 2009
  • 21. Do Some Work class MyWorker < BackgrounDRb::MetaWorker set_worker_name :my_worker def create(args = nil) # initialization goes here end def do_work(user_id = nil) # do some work end end def my_action flash[:notice] = quot;Processing ...quot; MiddleMan.worker(:my_worker).async_do_work(:arg => @user.id) end Thursday, April 30, 2009
  • 22. Persistent Work def my_action MiddleMan(:my_worker).enq_do_work(:job_key => quot;unique_keyquot;) end Thursday, April 30, 2009
  • 23. Poll Status class MyWorker < BackgrounDRb::MetaWorker set_worker_name :my_worker def create(args = nil) # initialization goes here end def do_work(user_id = nil) # do some work register_status quot;almost donequot; end end Thursday, April 30, 2009
  • 24. Poll Status def my_action @job_key = MiddleMan.new_worker( :worker => :my_worker, :job_key => quot;unique_keyquot; ) MiddleMan.worker(:my_worker, @job_key). do_work(@user.id) end def check_status @status = MiddleMan.worker(:my_worker, @job_key). ask_status end Thursday, April 30, 2009
  • 25. The Worker Process script/backgroundrb start Thursday, April 30, 2009
  • 26. BJ - Background Job http://codeforpeople.rubyforge.org/svn/bj Thursday, April 30, 2009
  • 27. Bj - Setup script/plugin install http:// codeforpeople.rubyforge.org/svn/rails/plugins/bj script/bj setup gem install bj require ‘bj’ bj setup Thursday, April 30, 2009
  • 28. Bj Schema create_table quot;bj_jobquot;, :primary_key => quot;bj_job_idquot; do |t| t.text quot;commandquot; t.text quot;statequot; t.integer quot;priorityquot; t.text quot;tagquot; t.integer quot;is_restartablequot; t.text quot;submitterquot; t.text quot;runnerquot; t.integer quot;pidquot; t.datetime quot;submitted_atquot; t.datetime quot;started_atquot; t.datetime quot;finished_atquot; t.text quot;envquot; t.text quot;stdinquot; t.text quot;stdoutquot; t.text quot;stderrquot; t.integer quot;exit_statusquot; end Thursday, April 30, 2009
  • 29. Bj Schema create_table quot;bj_job_archivequot;, :primary_key => quot;bj_job_archive_idquot; do |t| t.text quot;commandquot; t.text quot;statequot; t.integer quot;priorityquot; t.text quot;tagquot; t.integer quot;is_restartablequot; t.text quot;submitterquot; t.text quot;runnerquot; t.integer quot;pidquot; t.datetime quot;submitted_atquot; t.datetime quot;started_atquot; t.datetime quot;finished_atquot; t.datetime quot;archived_atquot; t.text quot;envquot; t.text quot;stdinquot; t.text quot;stdoutquot; t.text quot;stderrquot; t.integer quot;exit_statusquot; end Thursday, April 30, 2009
  • 30. Do Some Work def my_action flash[:notice] = quot;Processing ...quot; Bj.submit './script/runner /lib/do_some_work.rb' end def my_other_action flash[:notice] = quot;Processing ...quot; Bj.submit 'echo foobar', :tag => 'sample job' end Thursday, April 30, 2009
  • 31. The Worker Process bj run --forever --rails_env=development Thursday, April 30, 2009
  • 32. Delayed Job http://github.com/tobi/delayed_job/ Thursday, April 30, 2009
  • 33. Delayed Job Setup • script/plugin install git://github.com/ tobi/delayed_job.git • create a delayed jobs table Thursday, April 30, 2009
  • 34. Delayed Job Schema create_table quot;delayed_jobsquot; do |t| t.integer quot;priorityquot;, :default => 0 t.integer quot;attemptsquot;, :default => 0 t.text quot;handlerquot; t.string quot;last_errorquot; t.datetime quot;run_atquot; t.datetime quot;locked_atquot; t.datetime quot;failed_atquot; t.string quot;locked_byquot; t.datetime quot;created_atquot; t.datetime quot;updated_atquot; end Thursday, April 30, 2009
  • 35. Do Some Work class MyWorker attr_accessor :user_id def initialize(user) self.user_id = user_id end def perform User.find user_id # do some work end end Thursday, April 30, 2009
  • 36. Do Some Work def my_action flash[:notice] = quot;Processing ...quot; Delayed::Job.enqueue MyWorker.new(@user.id) end def my_action flash[:notice] = quot;Processing ...quot; MyMailer.new(@user.id).send_later(:deliver_newsletter) end Thursday, April 30, 2009
  • 37. The Worker Process rake jobs:work Thursday, April 30, 2009
  • 38. Workling http://github.com/purzelrakete/workling/ Thursday, April 30, 2009
  • 39. Workling Install script/plugin install git://github.com/purzelrakete/ workling.git Thursday, April 30, 2009
  • 40. Do Some Work class MyWorker < Workling::Base def do_something(options) # do some work end end def my_action flash[:notice] = quot;Processing ...quot; MyWorker.async_do_something :user_id => @user.id end Thursday, April 30, 2009
  • 41. The Worker Process with spawn: script/workling_client start with starling: sudo starling -d script/workling_client start Thursday, April 30, 2009
  • 42. Starling http://github.com/starling/starling/ Thursday, April 30, 2009
  • 43. Even More Options • Background Fu - http://github.com/ncr/ background-fu • Roofus Scheduler - http://github.com/ jmettraux/rufus-scheduler • AP4R - http://rubyforge.org/projects/ ap4r/ Thursday, April 30, 2009
  • 45. Kestrel http://github.com/robey/kestrel/ Thursday, April 30, 2009
  • 46. Rabbit MQ http://www.rabbitmq.com/ Thursday, April 30, 2009
  • 47. Active MQ http://activemq.apache.org/ Thursday, April 30, 2009
  • 48. Amazon SQS http://aws.amazon.com/sqs/ Thursday, April 30, 2009
  • 49. Monitoring • god - http://github.com/mojombo/ god/ • launchd - OS X • monit - http://mmonit.com/monit/ Thursday, April 30, 2009
  • 50. Persistant? Yes No Scaling concerns or fear I enjoy of commitment? managing a process? No Yes No Yes Delayed Job Background Job Spawn Workling Daemons Are you the Kestrel Starling Probably Not Yes next Twitter? Rabbit MQ Thursday, April 30, 2009
  • 51. Thanks rob@robmack.com twitter.com/robmack Thursday, April 30, 2009