SlideShare ist ein Scribd-Unternehmen logo
1 von 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?

Weitere ähnliche Inhalte

Was ist angesagt?

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 infrastructureRoman Imankulov
 
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 2014Puppet
 
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 MeetupAbel Muíño
 
Infrastructure = code - 1 year later
Infrastructure = code - 1 year laterInfrastructure = code - 1 year later
Infrastructure = code - 1 year laterChristian Ortner
 
Introduction to Python Celery
Introduction to Python CeleryIntroduction to Python Celery
Introduction to Python CeleryMahendra M
 
Ansible 2 and Ansible Galaxy 2
Ansible 2 and Ansible Galaxy 2Ansible 2 and Ansible Galaxy 2
Ansible 2 and Ansible Galaxy 2Jeff Geerling
 
Trying Continuous Delivery - pyconjp 2012
Trying Continuous Delivery - pyconjp 2012Trying Continuous Delivery - pyconjp 2012
Trying Continuous Delivery - pyconjp 2012Toru Furukawa
 
Celery: The Distributed Task Queue
Celery: The Distributed Task QueueCelery: The Distributed Task Queue
Celery: The Distributed Task QueueRichard Leland
 
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 2014Puppet
 
Asynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryAsynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryKishor Kumar
 
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 mqJeff Peck
 
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 SwarmWei Lin
 
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 PythonYurii Vasylenko
 
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.Workhorse Computing
 
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 VCRKerry Buckley
 

Was ist angesagt? (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
 

Andere mochten auch

Andere mochten auch (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
 

Ähnlich wie Background Jobs with Resque

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 applicaitontomi vanek
 
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 2015Masahiro Nagano
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Puppet Performance Profiling - CM Camp 2015
Puppet Performance Profiling - CM Camp 2015Puppet Performance Profiling - CM Camp 2015
Puppet Performance Profiling - CM Camp 2015ripienaar
 
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 FinagleGeoff Ballinger
 
To Batch Or Not To Batch
To Batch Or Not To BatchTo Batch Or Not To Batch
To Batch Or Not To BatchLuca Mearelli
 
Java APIs- The missing manual (concurrency)
Java APIs- The missing manual (concurrency)Java APIs- The missing manual (concurrency)
Java APIs- The missing manual (concurrency)Hendrik Ebbers
 
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 librarySusan Tan
 
Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}Matthew Eernisse, NodeJs, .toster {webdev}
Matthew Eernisse, NodeJs, .toster {webdev}.toster
 
BPM-3 Advanced Workflow Deep Dive
BPM-3 Advanced Workflow Deep DiveBPM-3 Advanced Workflow Deep Dive
BPM-3 Advanced Workflow Deep DiveAlfresco Software
 
Rails 3 (beta) Roundup
Rails 3 (beta) RoundupRails 3 (beta) Roundup
Rails 3 (beta) RoundupWayne Carter
 
Getting to know Laravel 5
Getting to know Laravel 5Getting to know Laravel 5
Getting to know Laravel 5Bukhori Aqid
 
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 OracleRaimonds 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 MizrahiRan Mizrahi
 
Ruby on Rails - Introduction
Ruby on Rails - IntroductionRuby on Rails - Introduction
Ruby on Rails - IntroductionVagmi Mudumbai
 

Ähnlich wie 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
 

Kürzlich hochgeladen

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 

Kürzlich hochgeladen (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 

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

Hinweis der Redaktion

  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