SlideShare una empresa de Scribd logo
1 de 39
Background Jobs with
      Resque
           Jon Homan
       Apprentice @ Obtiva

       http://jonhoman.com
           @jonhoman
Agenda
• Resque
• Examples
• Real world use
• Plugins
• Alternate Implementations
• When to use Resque
Background Jobs

• Remote API calls
• Uploading images
• Number crunching
• Updating RSS feeds
Resque
     https://github.com/defunkt/resque


• Open-source library for creating background
  jobs
• Redis backend
• Support for multiple queues
• Queues are processed by workers
More Resque Features
• Monitor with god or monit
• Distributed processing
• Priorities
• Persistent queues
• Memory leak resistant
• Web interface
resque-web
Redis
              http://redis.io/


• Key-value datastore
• data structure server
• constant time pushes and pops
• atomic operations
All “Foreground”
class FeedsController
 def create
   feed = Feed.create!
   feed.fetch
   redirect_to feed_path(feed)
 end
end

class Feed
 def fetch
   rss = RSS::Parse.parse(url, false)
   feed.title = rss.title
 end
end
Queue up creation
class FeedsController
 def create
  feed = Feed.create!
  Queue.push(feed) # won’t block UI
  redirect_to feed_path(feed)
 end
end

class Queue
 def push(feed)
  queue << feed
 end
end
Now with Resque
class FeedsController
 def create
  feed = Feed.create!
  Resque.enqueue(FeedCreator, feed.id)
  redirect_to feed_path(feed)
 end
end
How to process jobs
class FeedCreator
 @queue = :feed_creation

 def perform(feed_id)
   feed = Feed.find(feed_id)
   rss = RSS::Parser.parse(feed.url,false)
   feed.title = rss.title
   # create all items in the rss
 end
end
Workers?

• Long-running Rake tasks
• Look for jobs every n seconds
How to start workers
$ rake resque:work

$ QUEUE=feed rake resque:work

$ QUEUE=feed, twitter rake resque:work

$ QUEUE=* rake resque:work

$ COUNT=3 QUEUE=* rake resque:work
Testing w/ RSpec

it "stores the name of the feed" do
 FeedCreator.perform(feed.id)
 feed.reload.title.should == "Feed
end
Testing w/ RSpec

it "creates Items for every item in the feed" do
 FeedCreator.perform(feed.id)
 feed.reload.items.count.should == 5
end
Testing w/ RSpec

it “parses the feed” do
 RSS::Parser.should_receive(:parse)

 FeedCreator.perform(feed.id)
end
Real world uses


• GitHub
• Groupon
•   lifeStreams
GitHub
35 different types of jobs:
  • Warming caches
  • Counting disk usage
  • Building tarballs
  • Building Rubygems
  • Building graphs
  • Updating search index
Groupon

• Resque for background jobs
 • Notifications
 • Lockable worker
• Redis for semaphores
lifeStreams
• Process updates to blog feeds
• Publish updates to Facebook, Twitter, Email
Plugins
• resque_spec
• Resque Heroku Autoscaler
• resque multi step
• ResqueMailer
• resque-retry
• and at least 25 others
ResqueSpec
    https://github.com/leshill/resque_spec

• Resque plugin that adds resque-specific
  matchers
• have_queued
• have_scheduled
• have_queue_size_of
Examples
it “adds a feed to the creation queue” do
 post :create, :feed
 FeedCreator.should have_queued(feed.id)
end

it “schedules a feed update” do
 feed.update
 FeedUpdater.should have_scheduled(feed.id)
end
Resque Heroku
         Autoscaler

• Scales Heroku workers
• Start worker if none running
• Stops worker after jobs are processed
RHA
require 'resque/plugins/resque_heroku_autoscaler'

class TestJob
  extend Resque::Plugins::HerokuAutoscaler

  @queue = :test

  def perform
    ...awesome stuff...
  end
end
Resque Mailer


• Asynchronously deliver email in Rails
Resque Mailer

class MyMailer < ActionMailer::Base
  include Resque::Mailer
end


MyMailer.subject_email(params).deliver

QUEUE=mailer rake environment resque:work
resque-retry


• Retry, delay and exponential backoff support
resque-retry
require 'resque-retry'

class ExampleRetryJob
  extend Resque::Plugins::Retry
  @queue = :example_queue

  @retry_limit = 3
  @retry_delay = 60

  def self.perform(*args)
    # your magic/heavy lifting goes here.
  end
end
resque-retry

              no delay, 1m, 10m,   1h,    3h,    6h
@backoff_strategy = [0, 60, 600, 3600, 10800, 21600]
Alternate
           Implementations
•   C
•   Java
•   Scala
•   .NET
•   Python
•   PHP
•   node.js
jesque
// Add a job to the queue
final Job job = new Job("TestAction",
    new Object[]{ 1, 2, true, "test", Arrays.asList("inner",
4ß)});
final Client client = new ClientImpl(config);
client.enqueue("foo", job);
client.end();

// Start a worker to run jobs from the queue
final Worker worker = new WorkerImpl(config,
    Arrays.asList("foo"), Arrays.asList(TestAction.class));
final Thread workerThread = new Thread(worker);
workerThread.start();
Resque?

• Multiple queues
• Potentially HUGE queues
• Admin UI
• Expecting chaos/failures
DelayedJob?

• Numeric priorities
• Queue is small
• Add whole objects to queue
• No need to setup Redis
Do your homework
I didn’t
 (kinda)
Resources
github.com/defunkt/resque

redis.io

redistogo.com
Questions?

Más contenido relacionado

La actualidad más candente

Trying Continuous Delivery - pyconjp 2012
Trying Continuous Delivery - pyconjp 2012Trying Continuous Delivery - pyconjp 2012
Trying Continuous Delivery - pyconjp 2012
Toru Furukawa
 

La actualidad más candente (20)

Celery for internal API in SOA infrastructure
Celery for internal API in SOA infrastructureCelery for internal API in SOA infrastructure
Celery for internal API in SOA infrastructure
 
Introduction to Celery
Introduction to CeleryIntroduction to Celery
Introduction to Celery
 
Performance Tuning Your Puppet Infrastructure - PuppetConf 2014
Performance Tuning Your Puppet Infrastructure - PuppetConf 2014Performance Tuning Your Puppet Infrastructure - PuppetConf 2014
Performance Tuning Your Puppet Infrastructure - PuppetConf 2014
 
kRouter
kRouterkRouter
kRouter
 
Cachopo - Scalable Stateful Services - Madrid Elixir Meetup
Cachopo - Scalable Stateful Services - Madrid Elixir MeetupCachopo - Scalable Stateful Services - Madrid Elixir Meetup
Cachopo - Scalable Stateful Services - Madrid Elixir Meetup
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Infrastructure = code - 1 year later
Infrastructure = code - 1 year laterInfrastructure = code - 1 year later
Infrastructure = code - 1 year later
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python Celery
 
Ansible 2 and Ansible Galaxy 2
Ansible 2 and Ansible Galaxy 2Ansible 2 and Ansible Galaxy 2
Ansible 2 and Ansible Galaxy 2
 
Trying Continuous Delivery - pyconjp 2012
Trying Continuous Delivery - pyconjp 2012Trying Continuous Delivery - pyconjp 2012
Trying Continuous Delivery - pyconjp 2012
 
Designing net-aws-glacier
Designing net-aws-glacierDesigning net-aws-glacier
Designing net-aws-glacier
 
Celery
CeleryCelery
Celery
 
Celery: The Distributed Task Queue
Celery: The Distributed Task QueueCelery: The Distributed Task Queue
Celery: The Distributed Task Queue
 
The Puppet Master on the JVM - PuppetConf 2014
The Puppet Master on the JVM - PuppetConf 2014The Puppet Master on the JVM - PuppetConf 2014
The Puppet Master on the JVM - PuppetConf 2014
 
Asynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryAsynchronous Task Queues with Celery
Asynchronous Task Queues with Celery
 
Data processing with celery and rabbit mq
Data processing with celery and rabbit mqData processing with celery and rabbit mq
Data processing with celery and rabbit mq
 
Building Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker SwarmBuilding Distributed System with Celery on Docker Swarm
Building Distributed System with Celery on Docker Swarm
 
Controlling multiple VMs with the power of Python
Controlling multiple VMs with the power of PythonControlling multiple VMs with the power of Python
Controlling multiple VMs with the power of Python
 
Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.Selenium sandwich-3: Being where you aren't.
Selenium sandwich-3: Being where you aren't.
 
Testing http calls with Webmock and VCR
Testing http calls with Webmock and VCRTesting http calls with Webmock and VCR
Testing http calls with Webmock and VCR
 

Destacado

Lockout Tagout
Lockout TagoutLockout Tagout
Lockout Tagout
vtsiri
 
Fire Evacuation Plan
Fire Evacuation PlanFire Evacuation Plan
Fire Evacuation Plan
emmmily
 
Fire drill procedure
Fire drill procedureFire drill procedure
Fire drill procedure
Maria Hidalgo
 
Construction site safety
Construction site safetyConstruction site safety
Construction site safety
Debajit Roy
 
Unit 2. reinforcement
Unit 2. reinforcementUnit 2. reinforcement
Unit 2. reinforcement
Sonia
 

Destacado (20)

Loto training
Loto trainingLoto training
Loto training
 
Lockout Tagout
Lockout TagoutLockout Tagout
Lockout Tagout
 
Loto.ppt
Loto.pptLoto.ppt
Loto.ppt
 
Intro to basic fire alarm technology
Intro to basic fire alarm technologyIntro to basic fire alarm technology
Intro to basic fire alarm technology
 
Safety On Construction site
Safety On Construction siteSafety On Construction site
Safety On Construction site
 
Construction safety management
Construction safety managementConstruction safety management
Construction safety management
 
PPE
PPEPPE
PPE
 
Fire Evacuation Plan
Fire Evacuation PlanFire Evacuation Plan
Fire Evacuation Plan
 
Personal Protective Equipment
 Personal Protective Equipment Personal Protective Equipment
Personal Protective Equipment
 
Fire drill procedure
Fire drill procedureFire drill procedure
Fire drill procedure
 
Fire Alarm, Smoke Detector and Automatic Sprinkle System
Fire Alarm, Smoke Detector and Automatic Sprinkle SystemFire Alarm, Smoke Detector and Automatic Sprinkle System
Fire Alarm, Smoke Detector and Automatic Sprinkle System
 
fire detection and alarm system
fire detection and alarm systemfire detection and alarm system
fire detection and alarm system
 
Construction site safety
Construction site safetyConstruction site safety
Construction site safety
 
DETERMINATION ~ DO OR DIE
DETERMINATION ~ DO OR DIEDETERMINATION ~ DO OR DIE
DETERMINATION ~ DO OR DIE
 
Zoho1
Zoho1Zoho1
Zoho1
 
Tallinna üLikool
Tallinna üLikoolTallinna üLikool
Tallinna üLikool
 
Pokus214
Pokus214Pokus214
Pokus214
 
The Earth
The EarthThe Earth
The Earth
 
Hydrogen Progress, Priorities and Opportunities
Hydrogen Progress, Priorities and OpportunitiesHydrogen Progress, Priorities and Opportunities
Hydrogen Progress, Priorities and Opportunities
 
Unit 2. reinforcement
Unit 2. reinforcementUnit 2. reinforcement
Unit 2. reinforcement
 

Similar a Background Jobs with Resque

Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
.toster
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
Raimonds Simanovskis
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 

Similar a Background Jobs with Resque (20)

Django Celery
Django Celery Django Celery
Django Celery
 
Spring Batch in Code - simple DB to DB batch applicaiton
Spring Batch in Code - simple DB to DB batch applicaitonSpring Batch in Code - simple DB to DB batch applicaiton
Spring Batch in Code - simple DB to DB batch applicaiton
 
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015Rhebok, High Performance Rack Handler / Rubykaigi 2015
Rhebok, High Performance Rack Handler / Rubykaigi 2015
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Puppet Performance Profiling - CM Camp 2015
Puppet Performance Profiling - CM Camp 2015Puppet Performance Profiling - CM Camp 2015
Puppet Performance Profiling - CM Camp 2015
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To Batch
 
Java APIs- The missing manual (concurrency)
Java APIs- The missing manual (concurrency)Java APIs- The missing manual (concurrency)
Java APIs- The missing manual (concurrency)
 
Let's read code: python-requests library
Let's read code: python-requests libraryLet's read code: python-requests library
Let's read code: python-requests library
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}
 
BPM-3 Advanced Workflow Deep Dive
BPM-3 Advanced Workflow Deep DiveBPM-3 Advanced Workflow Deep Dive
BPM-3 Advanced Workflow Deep Dive
 
Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) Roundup
 
NodeJS
NodeJSNodeJS
NodeJS
 
Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5
 
Fast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on OracleFast Web Applications Development with Ruby on Rails on Oracle
Fast Web Applications Development with Ruby on Rails on Oracle
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
CakePHP
CakePHPCakePHP
CakePHP
 
Rails 4.0
Rails 4.0Rails 4.0
Rails 4.0
 
Mongo à la Resque
Mongo à la ResqueMongo à la Resque
Mongo à la Resque
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - Introduction
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+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...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Último (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
+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...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Background Jobs with Resque

  • 1. Background Jobs with Resque Jon Homan Apprentice @ Obtiva http://jonhoman.com @jonhoman
  • 2.
  • 3. Agenda • Resque • Examples • Real world use • Plugins • Alternate Implementations • When to use Resque
  • 4. Background Jobs • Remote API calls • Uploading images • Number crunching • Updating RSS feeds
  • 5. Resque https://github.com/defunkt/resque • Open-source library for creating background jobs • Redis backend • Support for multiple queues • Queues are processed by workers
  • 6. More Resque Features • Monitor with god or monit • Distributed processing • Priorities • Persistent queues • Memory leak resistant • Web interface
  • 8. Redis http://redis.io/ • Key-value datastore • data structure server • constant time pushes and pops • atomic operations
  • 9. All “Foreground” class FeedsController def create feed = Feed.create! feed.fetch redirect_to feed_path(feed) end end class Feed def fetch rss = RSS::Parse.parse(url, false) feed.title = rss.title end end
  • 10. Queue up creation class FeedsController def create feed = Feed.create! Queue.push(feed) # won’t block UI redirect_to feed_path(feed) end end class Queue def push(feed) queue << feed end end
  • 11. Now with Resque class FeedsController def create feed = Feed.create! Resque.enqueue(FeedCreator, feed.id) redirect_to feed_path(feed) end end
  • 12. How to process jobs class FeedCreator @queue = :feed_creation def perform(feed_id) feed = Feed.find(feed_id) rss = RSS::Parser.parse(feed.url,false) feed.title = rss.title # create all items in the rss end end
  • 13. Workers? • Long-running Rake tasks • Look for jobs every n seconds
  • 14. How to start workers $ rake resque:work $ QUEUE=feed rake resque:work $ QUEUE=feed, twitter rake resque:work $ QUEUE=* rake resque:work $ COUNT=3 QUEUE=* rake resque:work
  • 15. Testing w/ RSpec it "stores the name of the feed" do FeedCreator.perform(feed.id) feed.reload.title.should == "Feed end
  • 16. Testing w/ RSpec it "creates Items for every item in the feed" do FeedCreator.perform(feed.id) feed.reload.items.count.should == 5 end
  • 17. Testing w/ RSpec it “parses the feed” do RSS::Parser.should_receive(:parse) FeedCreator.perform(feed.id) end
  • 18. Real world uses • GitHub • Groupon • lifeStreams
  • 19. GitHub 35 different types of jobs: • Warming caches • Counting disk usage • Building tarballs • Building Rubygems • Building graphs • Updating search index
  • 20. Groupon • Resque for background jobs • Notifications • Lockable worker • Redis for semaphores
  • 21. lifeStreams • Process updates to blog feeds • Publish updates to Facebook, Twitter, Email
  • 22. Plugins • resque_spec • Resque Heroku Autoscaler • resque multi step • ResqueMailer • resque-retry • and at least 25 others
  • 23. ResqueSpec https://github.com/leshill/resque_spec • Resque plugin that adds resque-specific matchers • have_queued • have_scheduled • have_queue_size_of
  • 24. Examples it “adds a feed to the creation queue” do post :create, :feed FeedCreator.should have_queued(feed.id) end it “schedules a feed update” do feed.update FeedUpdater.should have_scheduled(feed.id) end
  • 25. Resque Heroku Autoscaler • Scales Heroku workers • Start worker if none running • Stops worker after jobs are processed
  • 26. RHA require 'resque/plugins/resque_heroku_autoscaler' class TestJob extend Resque::Plugins::HerokuAutoscaler @queue = :test def perform ...awesome stuff... end end
  • 27. Resque Mailer • Asynchronously deliver email in Rails
  • 28. Resque Mailer class MyMailer < ActionMailer::Base include Resque::Mailer end MyMailer.subject_email(params).deliver QUEUE=mailer rake environment resque:work
  • 29. resque-retry • Retry, delay and exponential backoff support
  • 30. resque-retry require 'resque-retry' class ExampleRetryJob extend Resque::Plugins::Retry @queue = :example_queue @retry_limit = 3 @retry_delay = 60 def self.perform(*args) # your magic/heavy lifting goes here. end end
  • 31. resque-retry no delay, 1m, 10m, 1h, 3h, 6h @backoff_strategy = [0, 60, 600, 3600, 10800, 21600]
  • 32. Alternate Implementations • C • Java • Scala • .NET • Python • PHP • node.js
  • 33. jesque // Add a job to the queue final Job job = new Job("TestAction", new Object[]{ 1, 2, true, "test", Arrays.asList("inner", 4ß)}); final Client client = new ClientImpl(config); client.enqueue("foo", job); client.end(); // Start a worker to run jobs from the queue final Worker worker = new WorkerImpl(config, Arrays.asList("foo"), Arrays.asList(TestAction.class)); final Thread workerThread = new Thread(worker); workerThread.start();
  • 34. Resque? • Multiple queues • Potentially HUGE queues • Admin UI • Expecting chaos/failures
  • 35. DelayedJob? • Numeric priorities • Queue is small • Add whole objects to queue • No need to setup Redis

Notas del editor

  1. \n
  2. Software consulting company in Chicago, IL.\n\nPrimarily RoR, but have mobile, Java, .NET project from time to time\n\nAlways looking for good developers. Interested? Find me after the talk\n
  3. \n
  4. Useful for cpu- and network-intensive tasks\n\nProcesses that run on an interval\n
  5. queue examples: \n* one for each email type; \n* one for updating feeds, one for posting to twitter\n\n
  6. priority is assigned per-worker; specified by queue\n\nMemory leak -&gt; worker forks a child process for every job\n
  7. \n
  8. Resque uses Redis as its database backend\n\ndata structure: string, hash, list, set\n\nlinked list gives great performance for insert/retrieve at head and tail\n\natomic operations: one action won&amp;#x2019;t stomp on another\n
  9. UI will block for each feed creation\nunder load, consume a ton of resources (each call to the controller forks a process???)\n
  10. \n
  11. enqueue takes a Ruby class and any number of arguments after that\n\nargs passed as JSON; can&amp;#x2019;t pass entire objects, pass an id\n
  12. \n
  13. 5 seconds is the default\n
  14. \n
  15. processors are POROs so testing is pretty straightforward\ntest side effects\n
  16. \n
  17. \n
  18. \n
  19. copies from Resque&amp;#x2019;s README\n
  20. semaphore - ensures a deal is still able to sold\n\natomic value of deal sales remaining across processess\n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. Ethan&amp;#x2019;s geekfest on nosql db&amp;#x2019;s - choose the right solution for the job\n\n
  37. I picked Resque as a learning tool\n\nBreakable Toys\n
  38. \n
  39. \n