SlideShare a Scribd company logo
celery
distributed task




                   @matclayton
warning
background
what is celery?
what is celery?



  "celery is an open source asynchronous task queue/
job
  queue based on distributed message I. It is focused
what is celery?



  "celery is an open source asynchronous task queue/
job
  queue based on distributed message passing. It is




but what does that
you can run


• distributed
• concurrently
• in the background
use cases


  • external api calls (twitter)
  • long running tasks (transcoding)
  • concurrent execution (batch image
    resize)
  • load balancing (across servers)
sql

      django   celery

      ORM      carro

               AMQP
      SQL        or
               STOMP
result


•   database
•   AMQP
•   cache
•   tokyo tyrant
•   redis
•   mongodb
components


1. views.py / management
   command
2. broker – RabbitMQ
3. workers
workflow




http://robertpogorzelski.com/blog/2009/09/10/rabbitmq-celery-
rabbits and
warrens
Django Celery
setting up the

 $ sudo apt-get install rabbitmq-
  server
 $ sudo pip install celery


$ rabbitmqctl add_user myuser
 mypassword
$ rabbitmqctl add_vhost myvhost
$ rabbitmqctl set_permissions -p
setup
        INSTALLED_APPS += ("djcelery", )      settings.p
        BROKER_HOST = "localhost"
        BROKER_PORT = 5672
        BROKER_USER = “myuser"
        BROKER_PASSWORD = “mypassword"
        BROKER_VHOST = “myvhost"

        CELERY_QUEUES = {
            "regular_tasks": {
                "binding_key": "task.#",
            },
            "twitter_tasks": {
                "binding_key": "twitter.#",
            },
            "feed_tasks": {
                "binding_key": "feed.#",
            },
        }


        $ python manage.py celeryd -B
hello

    from celery.decorators import task
                                         tasks.p
    @task
    def add(x, y):
      return x + y




    >>> result = add.delay(4, 4)
    >>> result.wait() # wait
    8
post to

from celery.task import Task
                                             tasks.p
class UpdateStatus(Task):
    name = "twitter.updatestatus"
    routing_key = 'twitter.updatestatus'
    ignore_result = True
        
    def run(self, tweet, **kwargs):
        post_to_twitter(tweet)
        

from twitter.tasks import UpdateStatus
UpdateStatus.delay(tweet=‘hello world’)
                                             views.p
retry / rate
from celery.task import Task
                                                    tasks.p
class UpdateStatus(Task):
    name = "twitter.updatestatus"
    routing_key = 'twitter.updatestatus'
    ignore_result = True
    default_retry_delay = 5 * 60
    max_retries = 12 # 1 hour retry
     rate_limit = ‘10/s’
    
    def run(self, tweet, **kwargs):
        try:
            post_to_twitter(tweet)
        except Exception, exc:
            # If twitter crashes retry
            self.retry([tweet,], kwargs, exc=exc)

from twitter.tasks import UpdateStatus              views.p
UpdateStatus.delay(tweet=‘hello world’)
podcast


from celery.task import PeriodicTask
                                                 tasks.p
class FeedImportPeriodicTask(PeriodicTask):
    run_every = timedelta(hours=1)
    routing_key = 'feed.periodic_import'

    def run(self, **kwargs):
        logger = self.get_logger(**kwargs)
        logger.info("Running Periodic Feed Import task!")
        update_podcasts(silent=False)
class FeedImporter(Task):
    name = "feed.import"
    routing_key = 'feed.import'
                                                                            tasks.p
    ignore_result = True
    default_retry_delay = 5 * 60 # retry in 5 minutes
    max_retries = 72 # 6 Hours to cover major outages

    def run(self, podcast_id, **kwargs):
        try:
            logger = self.get_logger(**kwargs)
            # The cache key consists of the task name and the MD5 digest of the feed id.
            lock_id = "%s-lock-%s" % (self.name, podcast_id)
            is_locked = lambda: str(cache.get(lock_id)) == "true"
            acquire_lock = lambda: cache.set(lock_id, "true", 300)
            # memcache delete is very slow, so we'd rather set a false value
            # with a very low expiry time.
            release_lock = lambda: cache.set(lock_id, "nil", 1)
    
            logger.debug("Trying to import feed: %s" % podcast_id)
            if is_locked():
                logger.debug("Feed %s is already being imported by another worker" % podcast_id)
                return

            acquire_lock()
            try:
                import_feed(logger, podcast_id)
            finally:
                release_lock()
        except Exception, exc:
            logger.error(exc)
typical




• running out of disk space ==
  rabbitmq fail
• queue priorities, difficult
• non-pickle-able errors
• crashing consumers
other cool


   •   tasksets / callbacks
   •   remote control tasks
   •   abortable tasks
   •   eta – run tasks at a set time
   •   HttpDispatchTask
   •   expiring tasks
   •   celerymon
   •   celeryev
   •   ajax views
finding




• http://github.com/ask/celery
• http://github.com/ask/django-
  celery
• irc.freenode.net #celery (asksol
  owner, always helpful and about)
@matclayton
mat@mixcloud.com

More Related Content

PDF
Celery: The Distributed Task Queue
PDF
Celery - A Distributed Task Queue
ODP
Europython 2011 - Playing tasks with Django & Celery
PDF
Celery
PDF
Data processing with celery and rabbit mq
PDF
Advanced task management with Celery
PDF
Celery with python
PDF
Life in a Queue - Using Message Queue with django
Celery: The Distributed Task Queue
Celery - A Distributed Task Queue
Europython 2011 - Playing tasks with Django & Celery
Celery
Data processing with celery and rabbit mq
Advanced task management with Celery
Celery with python
Life in a Queue - Using Message Queue with django

What's hot (20)

PPTX
Writer Monad for logging execution of functions
PDF
Practical Celery
PDF
Data Persistence in Android with Room Library
PPTX
Spring Boot and REST API
PPTX
Flower and celery
PDF
정규표현식(Regular expressions)
PDF
Java 8 Lambda Expressions & Streams
PDF
人狼知能プログラミング演習資料2015
PPTX
Corso js and angular
PDF
State: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVM
PDF
Introduction to Functional Programming with Scala
PDF
[2022]Flutter_IO_Extended_Korea_멀티모듈을활용한플러터클린아키텍처_...
PDF
Gradle Introduction
PDF
ZIO-Direct - Functional Scala 2022
PPT
Learn flask in 90mins
PPTX
PDF
Spring Data JPA
KEY
Fabric.js — Building a Canvas Library
PDF
Functional Programming 101 with Scala and ZIO @FunctionalWorld
PDF
Pengenalan Git
Writer Monad for logging execution of functions
Practical Celery
Data Persistence in Android with Room Library
Spring Boot and REST API
Flower and celery
정규표현식(Regular expressions)
Java 8 Lambda Expressions & Streams
人狼知能プログラミング演習資料2015
Corso js and angular
State: You're Doing It Wrong - Alternative Concurrency Paradigms For The JVM
Introduction to Functional Programming with Scala
[2022]Flutter_IO_Extended_Korea_멀티모듈을활용한플러터클린아키텍처_...
Gradle Introduction
ZIO-Direct - Functional Scala 2022
Learn flask in 90mins
Spring Data JPA
Fabric.js — Building a Canvas Library
Functional Programming 101 with Scala and ZIO @FunctionalWorld
Pengenalan Git
Ad

Viewers also liked (12)

PDF
Understanding Non Blocking I/O with Python
PDF
Building Distributed System with Celery on Docker Swarm
ODP
Introduction to Python Celery
PPTX
Celery in the Django
PDF
Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...
PDF
Celery by dummy
PDF
Scaling up task processing with Celery
PDF
Resftul API Web Development with Django Rest Framework & Celery
PDF
Distributed Task Processing with Celery - PyZH
PDF
Building Distributed System with Celery on Docker Swarm - PyCon JP 2016
PDF
An Introduction to Celery
PDF
Queue Everything and Please Everyone
Understanding Non Blocking I/O with Python
Building Distributed System with Celery on Docker Swarm
Introduction to Python Celery
Celery in the Django
Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...
Celery by dummy
Scaling up task processing with Celery
Resftul API Web Development with Django Rest Framework & Celery
Distributed Task Processing with Celery - PyZH
Building Distributed System with Celery on Docker Swarm - PyCon JP 2016
An Introduction to Celery
Queue Everything and Please Everyone
Ad

Similar to Django Celery (20)

KEY
Testing My Patience
PDF
KEY
Background Jobs with Resque
PDF
Debugging: Rules And Tools - PHPTek 11 Version
PDF
Debugging: Rules & Tools
PDF
Threads, Queues, and More: Async Programming in iOS
PDF
How to fake_properly
PDF
Google App Engine Developer - Day3
PDF
Introduction to Protractor
PDF
Akka Cluster in Java - JCConf 2015
KEY
Curator intro
PDF
Ten useful JavaScript tips & best practices
PDF
Automation with Ansible and Containers
KEY
DjangoCon US 2011 - Monkeying around at New Relic
KEY
Djangocon11: Monkeying around at New Relic
PDF
Тестирование и Django
PDF
Deixa para depois, Procrastinando com Celery em Python
PDF
Queue your work
PPTX
DevOps with Fabric
PDF
Python magicmethods
Testing My Patience
Background Jobs with Resque
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules & Tools
Threads, Queues, and More: Async Programming in iOS
How to fake_properly
Google App Engine Developer - Day3
Introduction to Protractor
Akka Cluster in Java - JCConf 2015
Curator intro
Ten useful JavaScript tips & best practices
Automation with Ansible and Containers
DjangoCon US 2011 - Monkeying around at New Relic
Djangocon11: Monkeying around at New Relic
Тестирование и Django
Deixa para depois, Procrastinando com Celery em Python
Queue your work
DevOps with Fabric
Python magicmethods

Recently uploaded (20)

PDF
Assigned Numbers - 2025 - Bluetooth® Document
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Accuracy of neural networks in brain wave diagnosis of schizophrenia
PPTX
Tartificialntelligence_presentation.pptx
PPTX
TLE Review Electricity (Electricity).pptx
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Getting Started with Data Integration: FME Form 101
PDF
Encapsulation theory and applications.pdf
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Empathic Computing: Creating Shared Understanding
PPT
Teaching material agriculture food technology
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
Assigned Numbers - 2025 - Bluetooth® Document
Heart disease approach using modified random forest and particle swarm optimi...
Programs and apps: productivity, graphics, security and other tools
Accuracy of neural networks in brain wave diagnosis of schizophrenia
Tartificialntelligence_presentation.pptx
TLE Review Electricity (Electricity).pptx
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
Encapsulation_ Review paper, used for researhc scholars
Getting Started with Data Integration: FME Form 101
Encapsulation theory and applications.pdf
OMC Textile Division Presentation 2021.pptx
Unlocking AI with Model Context Protocol (MCP)
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Agricultural_Statistics_at_a_Glance_2022_0.pdf
MIND Revenue Release Quarter 2 2025 Press Release
Empathic Computing: Creating Shared Understanding
Teaching material agriculture food technology
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Digital-Transformation-Roadmap-for-Companies.pptx

Django Celery

  • 5. what is celery? "celery is an open source asynchronous task queue/ job queue based on distributed message I. It is focused
  • 6. what is celery? "celery is an open source asynchronous task queue/ job queue based on distributed message passing. It is but what does that
  • 7. you can run • distributed • concurrently • in the background
  • 8. use cases • external api calls (twitter) • long running tasks (transcoding) • concurrent execution (batch image resize) • load balancing (across servers)
  • 9. sql django celery ORM carro AMQP SQL or STOMP
  • 10. result • database • AMQP • cache • tokyo tyrant • redis • mongodb
  • 11. components 1. views.py / management command 2. broker – RabbitMQ 3. workers
  • 15. setting up the $ sudo apt-get install rabbitmq- server $ sudo pip install celery $ rabbitmqctl add_user myuser mypassword $ rabbitmqctl add_vhost myvhost $ rabbitmqctl set_permissions -p
  • 16. setup INSTALLED_APPS += ("djcelery", ) settings.p BROKER_HOST = "localhost" BROKER_PORT = 5672 BROKER_USER = “myuser" BROKER_PASSWORD = “mypassword" BROKER_VHOST = “myvhost" CELERY_QUEUES = {     "regular_tasks": {         "binding_key": "task.#",     },     "twitter_tasks": {         "binding_key": "twitter.#",     },     "feed_tasks": {         "binding_key": "feed.#",     }, } $ python manage.py celeryd -B
  • 17. hello from celery.decorators import task tasks.p @task def add(x, y): return x + y >>> result = add.delay(4, 4) >>> result.wait() # wait 8
  • 18. post to from celery.task import Task tasks.p class UpdateStatus(Task):     name = "twitter.updatestatus"     routing_key = 'twitter.updatestatus'     ignore_result = True              def run(self, tweet, **kwargs):         post_to_twitter(tweet)          from twitter.tasks import UpdateStatus UpdateStatus.delay(tweet=‘hello world’) views.p
  • 19. retry / rate from celery.task import Task tasks.p class UpdateStatus(Task):     name = "twitter.updatestatus"     routing_key = 'twitter.updatestatus'     ignore_result = True     default_retry_delay = 5 * 60     max_retries = 12 # 1 hour retry rate_limit = ‘10/s’          def run(self, tweet, **kwargs):         try: post_to_twitter(tweet)         except Exception, exc:             # If twitter crashes retry             self.retry([tweet,], kwargs, exc=exc) from twitter.tasks import UpdateStatus views.p UpdateStatus.delay(tweet=‘hello world’)
  • 20. podcast from celery.task import PeriodicTask tasks.p class FeedImportPeriodicTask(PeriodicTask):     run_every = timedelta(hours=1)     routing_key = 'feed.periodic_import'     def run(self, **kwargs):         logger = self.get_logger(**kwargs)         logger.info("Running Periodic Feed Import task!")         update_podcasts(silent=False)
  • 21. class FeedImporter(Task):     name = "feed.import"     routing_key = 'feed.import' tasks.p     ignore_result = True     default_retry_delay = 5 * 60 # retry in 5 minutes     max_retries = 72 # 6 Hours to cover major outages     def run(self, podcast_id, **kwargs):         try:             logger = self.get_logger(**kwargs)             # The cache key consists of the task name and the MD5 digest of the feed id.             lock_id = "%s-lock-%s" % (self.name, podcast_id)             is_locked = lambda: str(cache.get(lock_id)) == "true"             acquire_lock = lambda: cache.set(lock_id, "true", 300)             # memcache delete is very slow, so we'd rather set a false value             # with a very low expiry time.             release_lock = lambda: cache.set(lock_id, "nil", 1)                  logger.debug("Trying to import feed: %s" % podcast_id)             if is_locked():                 logger.debug("Feed %s is already being imported by another worker" % podcast_id)                 return             acquire_lock()             try:                 import_feed(logger, podcast_id)             finally:                 release_lock()         except Exception, exc:             logger.error(exc)
  • 22. typical • running out of disk space == rabbitmq fail • queue priorities, difficult • non-pickle-able errors • crashing consumers
  • 23. other cool • tasksets / callbacks • remote control tasks • abortable tasks • eta – run tasks at a set time • HttpDispatchTask • expiring tasks • celerymon • celeryev • ajax views
  • 24. finding • http://github.com/ask/celery • http://github.com/ask/django- celery • irc.freenode.net #celery (asksol owner, always helpful and about)