SlideShare uma empresa Scribd logo
1 de 46
Baixar para ler 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

Mais conteúdo relacionado

Mais procurados

PFsense 방화벽 소개
PFsense 방화벽 소개PFsense 방화벽 소개
PFsense 방화벽 소개ajj007
 
Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task QueueDuy Do
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinFabio Collini
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolvedtrxcllnt
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event EmittersTheCreativedev Blog
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebBryan Helmig
 
Reactive Extensionsで非同期処理を簡単に
Reactive Extensionsで非同期処理を簡単にReactive Extensionsで非同期処理を簡単に
Reactive Extensionsで非同期処理を簡単にYoshifumi Kawai
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
Prometheus Celery Exporter
Prometheus Celery ExporterPrometheus Celery Exporter
Prometheus Celery ExporterFabio Todaro
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockitoshaunthomas999
 
CQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony applicationCQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony applicationSamuel ROZE
 
社内Java8勉強会 ラムダ式とストリームAPI
社内Java8勉強会 ラムダ式とストリームAPI社内Java8勉強会 ラムダ式とストリームAPI
社内Java8勉強会 ラムダ式とストリームAPIAkihiro Ikezoe
 
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
 

Mais procurados (20)

PFsense 방화벽 소개
PFsense 방화벽 소개PFsense 방화벽 소개
PFsense 방화벽 소개
 
Celery
CeleryCelery
Celery
 
Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task Queue
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 
RxJS Evolved
RxJS EvolvedRxJS Evolved
RxJS Evolved
 
Vertx
VertxVertx
Vertx
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
Event-sourced architectures with Akka
Event-sourced architectures with AkkaEvent-sourced architectures with Akka
Event-sourced architectures with Akka
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWeb
 
Django Celery
Django Celery Django Celery
Django Celery
 
Reactive Extensionsで非同期処理を簡単に
Reactive Extensionsで非同期処理を簡単にReactive Extensionsで非同期処理を簡単に
Reactive Extensionsで非同期処理を簡単に
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Spring boot
Spring bootSpring boot
Spring boot
 
Express js
Express jsExpress js
Express js
 
Celery with python
Celery with pythonCelery with python
Celery with python
 
Prometheus Celery Exporter
Prometheus Celery ExporterPrometheus Celery Exporter
Prometheus Celery Exporter
 
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and MockitoAn Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
 
CQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony applicationCQRS and Event Sourcing in a Symfony application
CQRS and Event Sourcing in a Symfony application
 
社内Java8勉強会 ラムダ式とストリームAPI
社内Java8勉強会 ラムダ式とストリームAPI社内Java8勉強会 ラムダ式とストリームAPI
社内Java8勉強会 ラムダ式とストリームAPI
 
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
 

Semelhante a 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
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play FrameworkKnoldus Inc.
 

Semelhante a 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
 
[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
 
Intoduction to Play Framework
Intoduction to Play FrameworkIntoduction to Play Framework
Intoduction to Play Framework
 

Mais de 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
 

Mais de 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
 

Último

Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
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
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
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
 
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
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
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
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
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
 
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
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
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
 
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
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
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
 

Último (20)

Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
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
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
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
 
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
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
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
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
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
 
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
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
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
 
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
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
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
 

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