SlideShare a Scribd company logo
1 of 46
Download to read offline
Celery
A Distributed Task Queue

                        Idan Gazit
 PyWeb-IL 8 / 29th September 2009
What is Celery?
Celery is a...
  Distributed
 Asynchronous
  Task Queue
  For Django
Celery is a...
  Distributed
 Asynchronous
  Task Queue
  For Django
Celery is a...
  Distributed
 Asynchronous
  Task Queue
  For Django
Celery is a...
  Distributed
 Asynchronous
  Task Queue
  For Django
Celery is a...
  Distributed
 Asynchronous
  Task Queue
              sin
  For Django 0.8 ce
What can I use it for?




                         http://www.flickr.com/photos/jabzg/2145312172/
Potential Uses
» Anything that needs to run
  asynchronously, e.g. outside of the
  request-response cycle.
» Background computation of ‘expensive
  queries’ (ex. denormalized counts)
» Interactions with external API’s
  (ex. Twitter)
» Periodic tasks (instead of cron & scripts)
» Long-running actions with results
  displayed via AJAX.
How does it work?




    http://www.flickr.com/photos/tomypelluz/14638999/
Celery Architecture
          AMQP      celery   task result
user
          broker   workers      store
Celery Architecture

user



       submit:
       tasks
       task sets
       periodic tasks
       retryable tasks
Celery Architecture
        AMQP          celery
        broker       workers




broker pushes
tasks to worker(s)
Celery Architecture
                     celery
                    workers




workers execute
tasks in parallel
(multiprocessing)
Celery Architecture
                             celery   task result
                            workers      store



task result (tombstone)
is written to task store:
‣RDBMS
‣memcached
‣Tokyo Tyrant
‣MongoDB
‣AMQP (new in 0.8)
Celery Architecture
                            task result
user
                               store
         read task result
Celery Architecture

Celery    uses...

Carrot    to talk to...

AMQP
Broker
Celery Architecture

Celery    pip install celery



Carrot    (dependency of celery)


AMQP
Broker
Celery Architecture

 Celery    pip install celery



 Carrot    (dependency of celery)



RabbitMQ   http://www.rabbitmq.com
AMQP is... Complex.
AMQP is Complex

» VHost        » Routing Keys

» Exchanges    » Bindings

 » Direct      » Queues

 » Fanout        » Durable

 » Topic         » Temporary

                 » Auto-Delete
bit.ly/amqp_intro
I Can Haz Celery?
Adding Celery

1. get & install an AMQP broker
  (pay attention to vhosts, permissions)

2. add Celery to INSTALLED_APPS

3. add a few settings:
  AMQP_SERVER = "localhost"
  AMQP_PORT = 5672
  AMQP_USER = "myuser"
  AMQP_PASSWORD = "mypassword"
  AMQP_VHOST = "myvhost"


4. manage.py syncdb
Celery Workers


» Run at least 1 celery worker server

» manage.py celeryd
  (--detatch for production)

» Can be on different machines

» Celery guarantees that tasks are only
  executed once
Tasks
Tasks


» Define tasks in your app

» app_name/tasks.py

» register & autodiscovery
  (like admin.py)
Task

from celery.task import Task
from celery.registry import tasks

class FetchUserInfoTask(Task):
    def run(self, screen_name, **kwargs):
        logger = self.get_logger(**kwargs)
        try:
             user = twitter.users.show(id=screen_name)
             logger.debug("Successfully fetched {0}".format(screen_name))
        except TwitterError:
             logger.error("Unable to fetch {0}: {1}".format(
                 screen_name, TwitterError))
            raise

        return user

tasks.register(FetchUserInfoTask)
Run It!




>>> from myapp.tasks import FetchUserInfoTask
>>> result = FetchUserInfoTask.delay('idangazit')
Task Result
» result.ready()
  true if task has finished

» result.result
  the return value of the task or exception
  instance if the task failed

» result.get()
  blocks until the task is complete then
  returns result or exception

» result.successful()
  returns True/False of task success
Why even check results?
Chained Tasks
from celery.task import Task
from celery.registry import tasks

class FetchUserInfoTask(Task):
    def run(self, screen_name, **kwargs):
        logger = self.get_logger(**kwargs)
        try:
             user = twitter.users.show(id=screen_name)
             logger.debug("Successfully fetched {0}".format(screen_name))
        except TwitterError:
             logger.error("Unable to fetch {0}: {1}".format(
                 screen_name, TwitterError))
            raise
        else:
             ProcessUserTask.delay(user)

        return user

tasks.register(FetchUserInfoTask)
Task Retries
Task Retries
from celery.task import Task
from celery.registry import tasks

class FetchUserInfoTask(Task):
    default_retry_delay = 5 * 60 # retry in 5 minutes
    max_retries = 5

   def run(self, screen_name, **kwargs):
       logger = self.get_logger(**kwargs)
       try:
            user = twitter.users.show(id=screen_name)
            logger.debug("Successfully fetched {0}".format(screen_name))
       except TwitterError, exc:
           self.retry(args=[screen_name,], kwargs=**kwargs, exc)
       else:
            ProcessUserTask.delay(user)

       return user

tasks.register(FetchUserInfoTask)
Periodic Tasks
Periodic Tasks

from celery.task import PeriodicTask
from celery.registry import tasks
from datetime import timedelta

class FetchMentionsTask(Task):
    run_every = timedelta(seconds=60)

   def run(self, **kwargs):
       logger = self.get_logger(**kwargs)
       mentions = twitter.statuses.mentions()
       for m in mentions:
           ProcessMentionTask.delay(m)

       return len(mentions)

tasks.register(FetchMentionsTask)
Task Sets
Task Sets


>>> from myapp.tasks import FetchUserInfoTask
>>> from celery.task import TaskSet
>>> ts = TaskSet(FetchUserInfoTask, args=(
            ['ahikman'], {},
            ['idangazit'], {},
            ['daonb'], {},
            ['dibau_naum_h'], {}))
>>> ts_result = ts.run()
>>> list_of_return_values = ts.join()
MOAR SELRY!
Celery.Views
Celery.Views

» Celery ships with some django views for
  launching /getting the status of tasks.
» JSON views perfect for use in your AJAX
  (err, AJAJ) calls.
» celery.views.apply(request, task_name, *args)

» celery.views.is_task_done(request, task_id)

» celery.views.task_status(request, task_id)
Routable Tasks
Routable Tasks

» "I want tasks of type X to only execute on
  this specific server"
» Some extra settings in settings.py:
  CELERY_AMQP_EXCHANGE = "tasks"
  CELERY_AMQP_PUBLISHER_ROUTING_KEY = "task.regular"
  CELERY_AMQP_EXCHANGE_TYPE = "topic"
  CELERY_AMQP_CONSUMER_QUEUE = "foo_tasks"
  CELERY_AMQP_CONSUMER_ROUTING_KEY = "foo.#"


» set the task's routing key:
  class MyRoutableTask(Task):
      routing_key = 'foo.bars'
like django, it's just python.
Support
             #celery on freenode
http://groups.google.com/group/celery-users/

    AskSol (the author) is friendly & helpful
Fin.
   @idangazit
idan@pixane.com

More Related Content

What's hot

Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSBrainhub
 
Celery: The Distributed Task Queue
Celery: The Distributed Task QueueCelery: The Distributed Task Queue
Celery: The Distributed Task QueueRichard Leland
 
Scaling up task processing with Celery
Scaling up task processing with CeleryScaling up task processing with Celery
Scaling up task processing with CeleryNicolas Grasset
 
A simple introduction to redis
A simple introduction to redisA simple introduction to redis
A simple introduction to redisZhichao Liang
 
[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020Ji-Woong Choi
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLJohn David Duncan
 
RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)Tracy Lee
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSAbul Hasan
 
Introduction to Nginx
Introduction to NginxIntroduction to Nginx
Introduction to NginxKnoldus Inc.
 
Developing RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBDeveloping RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBNicola Iarocci
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolvedtrxcllnt
 
19 08-22 introduction to activeMQ
19 08-22 introduction to activeMQ19 08-22 introduction to activeMQ
19 08-22 introduction to activeMQWoo Young Choi
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentationGene Chang
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx InternalsJoshua Zhu
 
Concurrent Programming Using the Disruptor
Concurrent Programming Using the DisruptorConcurrent Programming Using the Disruptor
Concurrent Programming Using the DisruptorTrisha Gee
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React AlicanteIgnacio Martín
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programmingFilip Ekberg
 

What's hot (20)

Celery with python
Celery with pythonCelery with python
Celery with python
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Celery: The Distributed Task Queue
Celery: The Distributed Task QueueCelery: The Distributed Task Queue
Celery: The Distributed Task Queue
 
Scaling up task processing with Celery
Scaling up task processing with CeleryScaling up task processing with Celery
Scaling up task processing with Celery
 
A simple introduction to redis
A simple introduction to redisA simple introduction to redis
A simple introduction to redis
 
[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020[오픈소스컨설팅] 스카우터 사용자 가이드 2020
[오픈소스컨설팅] 스카우터 사용자 가이드 2020
 
Developing for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQLDeveloping for Node.JS with MySQL and NoSQL
Developing for Node.JS with MySQL and NoSQL
 
Nginx
NginxNginx
Nginx
 
RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)RxJS Operators - Real World Use Cases (FULL VERSION)
RxJS Operators - Real World Use Cases (FULL VERSION)
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Introduction to Nginx
Introduction to NginxIntroduction to Nginx
Introduction to Nginx
 
Developing RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDBDeveloping RESTful Web APIs with Python, Flask and MongoDB
Developing RESTful Web APIs with Python, Flask and MongoDB
 
ELK Stack
ELK StackELK Stack
ELK Stack
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
 
19 08-22 introduction to activeMQ
19 08-22 introduction to activeMQ19 08-22 introduction to activeMQ
19 08-22 introduction to activeMQ
 
Akka Actor presentation
Akka Actor presentationAkka Actor presentation
Akka Actor presentation
 
Nginx Internals
Nginx InternalsNginx Internals
Nginx Internals
 
Concurrent Programming Using the Disruptor
Concurrent Programming Using the DisruptorConcurrent Programming Using the Disruptor
Concurrent Programming Using the Disruptor
 
Redux Sagas - React Alicante
Redux Sagas - React AlicanteRedux Sagas - React Alicante
Redux Sagas - React Alicante
 
Asynchronous programming
Asynchronous programmingAsynchronous programming
Asynchronous programming
 

Similar to An Introduction to Celery

Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSTechWell
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade ServerlessKatyShimizu
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade ServerlessKatyShimizu
 
Asynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryAsynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryKishor Kumar
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3Simon Su
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Deixa para depois, Procrastinando com Celery em Python
Deixa para depois, Procrastinando com Celery em PythonDeixa para depois, Procrastinando com Celery em Python
Deixa para depois, Procrastinando com Celery em PythonAdriano Petrich
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'sAntônio Roberto Silva
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Slaven tomac unit testing in angular js
Slaven tomac   unit testing in angular jsSlaven tomac   unit testing in angular js
Slaven tomac unit testing in angular jsSlaven Tomac
 
GPerf Using Jesque
GPerf Using JesqueGPerf Using Jesque
GPerf Using Jesquectoestreich
 
apidays LIVE Australia - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...apidays LIVE Australia - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...apidays
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgetsscottw
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTPMustafa TURAN
 
Forge - DevCon 2016: Building a Drone Imagery Service
Forge - DevCon 2016: Building a Drone Imagery ServiceForge - DevCon 2016: Building a Drone Imagery Service
Forge - DevCon 2016: Building a Drone Imagery ServiceAutodesk
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 

Similar to An Introduction to Celery (20)

Threads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOSThreads, Queues, and More: Async Programming in iOS
Threads, Queues, and More: Async Programming in iOS
 
Django Celery
Django Celery Django Celery
Django Celery
 
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
[NDC 2019] Functions 2.0: Enterprise-Grade Serverless
 
[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless[NDC 2019] Enterprise-Grade Serverless
[NDC 2019] Enterprise-Grade Serverless
 
Celery
CeleryCelery
Celery
 
Asynchronous Task Queues with Celery
Asynchronous Task Queues with CeleryAsynchronous Task Queues with Celery
Asynchronous Task Queues with Celery
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Deixa para depois, Procrastinando com Celery em Python
Deixa para depois, Procrastinando com Celery em PythonDeixa para depois, Procrastinando com Celery em Python
Deixa para depois, Procrastinando com Celery em Python
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
JavaCro'14 - Unit testing in AngularJS – Slaven TomacJavaCro'14 - Unit testing in AngularJS – Slaven Tomac
JavaCro'14 - Unit testing in AngularJS – Slaven Tomac
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Slaven tomac unit testing in angular js
Slaven tomac   unit testing in angular jsSlaven tomac   unit testing in angular js
Slaven tomac unit testing in angular js
 
GPerf Using Jesque
GPerf Using JesqueGPerf Using Jesque
GPerf Using Jesque
 
apidays LIVE Australia - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...apidays LIVE Australia - Building distributed systems on the shoulders of gia...
apidays LIVE Australia - Building distributed systems on the shoulders of gia...
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgets
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
 
Forge - DevCon 2016: Building a Drone Imagery Service
Forge - DevCon 2016: Building a Drone Imagery ServiceForge - DevCon 2016: Building a Drone Imagery Service
Forge - DevCon 2016: Building a Drone Imagery Service
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 

More from Idan Gazit

Datadesignmeaning
DatadesignmeaningDatadesignmeaning
DatadesignmeaningIdan Gazit
 
Designers Make It Go to Eleven!
Designers Make It Go to Eleven!Designers Make It Go to Eleven!
Designers Make It Go to Eleven!Idan Gazit
 
Web typography
Web typographyWeb typography
Web typographyIdan Gazit
 
CSS for Designers
CSS for DesignersCSS for Designers
CSS for DesignersIdan Gazit
 
CSS for Designers
CSS for DesignersCSS for Designers
CSS for DesignersIdan Gazit
 
CSS: selectors and the box model
CSS: selectors and the box modelCSS: selectors and the box model
CSS: selectors and the box modelIdan Gazit
 
CSS: selectors and the box model
CSS: selectors and the box modelCSS: selectors and the box model
CSS: selectors and the box modelIdan Gazit
 
Repeatable Deployments and Installations
Repeatable Deployments and InstallationsRepeatable Deployments and Installations
Repeatable Deployments and InstallationsIdan Gazit
 
Django 1.1 Tour
Django 1.1 TourDjango 1.1 Tour
Django 1.1 TourIdan Gazit
 

More from Idan Gazit (11)

Datadesignmeaning
DatadesignmeaningDatadesignmeaning
Datadesignmeaning
 
Designers Make It Go to Eleven!
Designers Make It Go to Eleven!Designers Make It Go to Eleven!
Designers Make It Go to Eleven!
 
Web typography
Web typographyWeb typography
Web typography
 
CSS Extenders
CSS ExtendersCSS Extenders
CSS Extenders
 
CSS for Designers
CSS for DesignersCSS for Designers
CSS for Designers
 
CSS for Designers
CSS for DesignersCSS for Designers
CSS for Designers
 
CSS: selectors and the box model
CSS: selectors and the box modelCSS: selectors and the box model
CSS: selectors and the box model
 
CSS: selectors and the box model
CSS: selectors and the box modelCSS: selectors and the box model
CSS: selectors and the box model
 
Why Django
Why DjangoWhy Django
Why Django
 
Repeatable Deployments and Installations
Repeatable Deployments and InstallationsRepeatable Deployments and Installations
Repeatable Deployments and Installations
 
Django 1.1 Tour
Django 1.1 TourDjango 1.1 Tour
Django 1.1 Tour
 

Recently uploaded

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
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
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
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
 
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
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 

Recently uploaded (20)

DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
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
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
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
 
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
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 

An Introduction to Celery

  • 1. Celery A Distributed Task Queue Idan Gazit PyWeb-IL 8 / 29th September 2009
  • 3. Celery is a... Distributed Asynchronous Task Queue For Django
  • 4. Celery is a... Distributed Asynchronous Task Queue For Django
  • 5. Celery is a... Distributed Asynchronous Task Queue For Django
  • 6. Celery is a... Distributed Asynchronous Task Queue For Django
  • 7. Celery is a... Distributed Asynchronous Task Queue sin For Django 0.8 ce
  • 8. What can I use it for? http://www.flickr.com/photos/jabzg/2145312172/
  • 9. Potential Uses » Anything that needs to run asynchronously, e.g. outside of the request-response cycle. » Background computation of ‘expensive queries’ (ex. denormalized counts) » Interactions with external API’s (ex. Twitter) » Periodic tasks (instead of cron & scripts) » Long-running actions with results displayed via AJAX.
  • 10. How does it work? http://www.flickr.com/photos/tomypelluz/14638999/
  • 11. Celery Architecture AMQP celery task result user broker workers store
  • 12. Celery Architecture user submit: tasks task sets periodic tasks retryable tasks
  • 13. Celery Architecture AMQP celery broker workers broker pushes tasks to worker(s)
  • 14. Celery Architecture celery workers workers execute tasks in parallel (multiprocessing)
  • 15. Celery Architecture celery task result workers store task result (tombstone) is written to task store: ‣RDBMS ‣memcached ‣Tokyo Tyrant ‣MongoDB ‣AMQP (new in 0.8)
  • 16. Celery Architecture task result user store read task result
  • 17. Celery Architecture Celery uses... Carrot to talk to... AMQP Broker
  • 18. Celery Architecture Celery pip install celery Carrot (dependency of celery) AMQP Broker
  • 19. Celery Architecture Celery pip install celery Carrot (dependency of celery) RabbitMQ http://www.rabbitmq.com
  • 21. AMQP is Complex » VHost » Routing Keys » Exchanges » Bindings » Direct » Queues » Fanout » Durable » Topic » Temporary » Auto-Delete
  • 23. I Can Haz Celery?
  • 24. Adding Celery 1. get & install an AMQP broker (pay attention to vhosts, permissions) 2. add Celery to INSTALLED_APPS 3. add a few settings: AMQP_SERVER = "localhost" AMQP_PORT = 5672 AMQP_USER = "myuser" AMQP_PASSWORD = "mypassword" AMQP_VHOST = "myvhost" 4. manage.py syncdb
  • 25. Celery Workers » Run at least 1 celery worker server » manage.py celeryd (--detatch for production) » Can be on different machines » Celery guarantees that tasks are only executed once
  • 26. Tasks
  • 27. Tasks » Define tasks in your app » app_name/tasks.py » register & autodiscovery (like admin.py)
  • 28. Task from celery.task import Task from celery.registry import tasks class FetchUserInfoTask(Task): def run(self, screen_name, **kwargs): logger = self.get_logger(**kwargs) try: user = twitter.users.show(id=screen_name) logger.debug("Successfully fetched {0}".format(screen_name)) except TwitterError: logger.error("Unable to fetch {0}: {1}".format( screen_name, TwitterError)) raise return user tasks.register(FetchUserInfoTask)
  • 29. Run It! >>> from myapp.tasks import FetchUserInfoTask >>> result = FetchUserInfoTask.delay('idangazit')
  • 30. Task Result » result.ready() true if task has finished » result.result the return value of the task or exception instance if the task failed » result.get() blocks until the task is complete then returns result or exception » result.successful() returns True/False of task success
  • 31. Why even check results?
  • 32. Chained Tasks from celery.task import Task from celery.registry import tasks class FetchUserInfoTask(Task): def run(self, screen_name, **kwargs): logger = self.get_logger(**kwargs) try: user = twitter.users.show(id=screen_name) logger.debug("Successfully fetched {0}".format(screen_name)) except TwitterError: logger.error("Unable to fetch {0}: {1}".format( screen_name, TwitterError)) raise else: ProcessUserTask.delay(user) return user tasks.register(FetchUserInfoTask)
  • 34. Task Retries from celery.task import Task from celery.registry import tasks class FetchUserInfoTask(Task): default_retry_delay = 5 * 60 # retry in 5 minutes max_retries = 5 def run(self, screen_name, **kwargs): logger = self.get_logger(**kwargs) try: user = twitter.users.show(id=screen_name) logger.debug("Successfully fetched {0}".format(screen_name)) except TwitterError, exc: self.retry(args=[screen_name,], kwargs=**kwargs, exc) else: ProcessUserTask.delay(user) return user tasks.register(FetchUserInfoTask)
  • 36. Periodic Tasks from celery.task import PeriodicTask from celery.registry import tasks from datetime import timedelta class FetchMentionsTask(Task): run_every = timedelta(seconds=60) def run(self, **kwargs): logger = self.get_logger(**kwargs) mentions = twitter.statuses.mentions() for m in mentions: ProcessMentionTask.delay(m) return len(mentions) tasks.register(FetchMentionsTask)
  • 38. Task Sets >>> from myapp.tasks import FetchUserInfoTask >>> from celery.task import TaskSet >>> ts = TaskSet(FetchUserInfoTask, args=( ['ahikman'], {}, ['idangazit'], {}, ['daonb'], {}, ['dibau_naum_h'], {})) >>> ts_result = ts.run() >>> list_of_return_values = ts.join()
  • 41. Celery.Views » Celery ships with some django views for launching /getting the status of tasks. » JSON views perfect for use in your AJAX (err, AJAJ) calls. » celery.views.apply(request, task_name, *args) » celery.views.is_task_done(request, task_id) » celery.views.task_status(request, task_id)
  • 43. Routable Tasks » "I want tasks of type X to only execute on this specific server" » Some extra settings in settings.py: CELERY_AMQP_EXCHANGE = "tasks" CELERY_AMQP_PUBLISHER_ROUTING_KEY = "task.regular" CELERY_AMQP_EXCHANGE_TYPE = "topic" CELERY_AMQP_CONSUMER_QUEUE = "foo_tasks" CELERY_AMQP_CONSUMER_ROUTING_KEY = "foo.#" » set the task's routing key: class MyRoutableTask(Task): routing_key = 'foo.bars'
  • 44. like django, it's just python.
  • 45. Support #celery on freenode http://groups.google.com/group/celery-users/ AskSol (the author) is friendly & helpful
  • 46. Fin. @idangazit idan@pixane.com