SlideShare une entreprise Scribd logo
1  sur  51
Télécharger pour lire hors ligne
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

Contenu connexe

Similaire à Background Processing in Ruby on Rails

Disconnecting the Database with ActiveRecord
Disconnecting the Database with ActiveRecordDisconnecting the Database with ActiveRecord
Disconnecting the Database with ActiveRecordBen 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 CucumberBen Mabey
 
ruby test-all parallel running
ruby test-all parallel runningruby test-all parallel running
ruby test-all parallel runningShota Fukumori
 
Ruby Isn't Just About Rails
Ruby Isn't Just About RailsRuby Isn't Just About Rails
Ruby Isn't Just About RailsAdam Wiggins
 
Page Caching Resurrected: A Fairy Tale
Page Caching Resurrected: A Fairy TalePage Caching Resurrected: A Fairy Tale
Page Caching Resurrected: A Fairy TaleBen Scofield
 
Impacta - Show Day de Rails
Impacta - Show Day de RailsImpacta - Show Day de Rails
Impacta - Show Day de RailsFabio 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 Everythingnoelrap
 
Automated Testing with Ruby
Automated Testing with RubyAutomated Testing with Ruby
Automated Testing with RubyKeith 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 2009Jan Wedekind
 
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 RailsRafael 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 meetMatt Aimonetti
 
Fixture Replacement Plugins
Fixture Replacement PluginsFixture Replacement Plugins
Fixture Replacement PluginsPaul Klipp
 
Debugging and Error handling
Debugging and Error handlingDebugging and Error handling
Debugging and Error handlingSuite Solutions
 
Ruby Metaprogramming
Ruby MetaprogrammingRuby Metaprogramming
Ruby MetaprogrammingThaichor Seng
 

Similaire à 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
 

Dernier

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 

Dernier (20)

From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 

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