SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Playing tasks with Django & Celery Mauro Rocco @fireantology
About me About Jamendo ,[object Object]
Free Music for users
Popularity and earnings for artists
Music licensing and background music at competitive prices for companies  ,[object Object]
Python, Javascript, PHP, Java/Android
celery contributor (just one of the hundreds )
Jamendo needs ,[object Object]
Statistics (downloads, listens, reviews, stars, fb likes) on different units
Music analysis trough external services
Music qualification trough several sources
Integration with third part services
Common jobs (contract generations, certifications, bills, search index update)
Celery ,[object Object]
Concurrency within a box
Distributed (across machines)
Scheduling (interval, cron, ...)
Fault tolerant
Subtask, Set of tasks
Web monitoring (django-celery and others)  “ Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well”
AMPQ The Advanced Message Queuing Protocol (AMQP) is an open standard application layer protocol for Message Oriented Middleware.
Celery schema
Celery worker ,[object Object]
Can serve one or multiple queues
Have a max number of tasks that can be executed at the same time
Can be remotely controlled

Weitere ähnliche Inhalte

Was ist angesagt?

Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
SANG WON PARK
 
NginxとLuaを用いた動的なリバースプロキシでデプロイを 100 倍速くした
NginxとLuaを用いた動的なリバースプロキシでデプロイを 100 倍速くしたNginxとLuaを用いた動的なリバースプロキシでデプロイを 100 倍速くした
NginxとLuaを用いた動的なリバースプロキシでデプロイを 100 倍速くした
toshi_pp
 

Was ist angesagt? (20)

Celery - A Distributed Task Queue
Celery - A Distributed Task QueueCelery - A Distributed Task Queue
Celery - A Distributed Task Queue
 
いまさら聞けないPostgreSQL運用管理
いまさら聞けないPostgreSQL運用管理いまさら聞けないPostgreSQL運用管理
いまさら聞けないPostgreSQL運用管理
 
[215]네이버콘텐츠통계서비스소개 김기영
[215]네이버콘텐츠통계서비스소개 김기영[215]네이버콘텐츠통계서비스소개 김기영
[215]네이버콘텐츠통계서비스소개 김기영
 
Deploying Flink on Kubernetes - David Anderson
 Deploying Flink on Kubernetes - David Anderson Deploying Flink on Kubernetes - David Anderson
Deploying Flink on Kubernetes - David Anderson
 
Real Time UI with Apache Kafka Streaming Analytics of Fast Data and Server Push
Real Time UI with Apache Kafka Streaming Analytics of Fast Data and Server PushReal Time UI with Apache Kafka Streaming Analytics of Fast Data and Server Push
Real Time UI with Apache Kafka Streaming Analytics of Fast Data and Server Push
 
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
Apache kafka 모니터링을 위한 Metrics 이해 및 최적화 방안
 
[2019] Java에서 Fiber를 이용하여 동시성concurrency 프로그래밍 쉽게 하기
[2019] Java에서 Fiber를 이용하여 동시성concurrency 프로그래밍 쉽게 하기[2019] Java에서 Fiber를 이용하여 동시성concurrency 프로그래밍 쉽게 하기
[2019] Java에서 Fiber를 이용하여 동시성concurrency 프로그래밍 쉽게 하기
 
NginxとLuaを用いた動的なリバースプロキシでデプロイを 100 倍速くした
NginxとLuaを用いた動的なリバースプロキシでデプロイを 100 倍速くしたNginxとLuaを用いた動的なリバースプロキシでデプロイを 100 倍速くした
NginxとLuaを用いた動的なリバースプロキシでデプロイを 100 倍速くした
 
乗っ取れコンテナ!!開発者から見たコンテナセキュリティの考え方(CloudNative Days Tokyo 2021 発表資料)
乗っ取れコンテナ!!開発者から見たコンテナセキュリティの考え方(CloudNative Days Tokyo 2021 発表資料)乗っ取れコンテナ!!開発者から見たコンテナセキュリティの考え方(CloudNative Days Tokyo 2021 発表資料)
乗っ取れコンテナ!!開発者から見たコンテナセキュリティの考え方(CloudNative Days Tokyo 2021 発表資料)
 
kpackによるコンテナイメージのビルド
kpackによるコンテナイメージのビルドkpackによるコンテナイメージのビルド
kpackによるコンテナイメージのビルド
 
Custom DevOps Monitoring System in MelOn (with InfluxDB + Telegraf + Grafana)
Custom DevOps Monitoring System in MelOn (with InfluxDB + Telegraf + Grafana)Custom DevOps Monitoring System in MelOn (with InfluxDB + Telegraf + Grafana)
Custom DevOps Monitoring System in MelOn (with InfluxDB + Telegraf + Grafana)
 
High Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando PatroniHigh Availability PostgreSQL with Zalando Patroni
High Availability PostgreSQL with Zalando Patroni
 
Best practices for MySQL High Availability Tutorial
Best practices for MySQL High Availability TutorialBest practices for MySQL High Availability Tutorial
Best practices for MySQL High Availability Tutorial
 
Running Kafka On Kubernetes With Strimzi For Real-Time Streaming Applications
Running Kafka On Kubernetes With Strimzi For Real-Time Streaming ApplicationsRunning Kafka On Kubernetes With Strimzi For Real-Time Streaming Applications
Running Kafka On Kubernetes With Strimzi For Real-Time Streaming Applications
 
今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -
今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -
今からでも遅くないDBマイグレーション - Flyway と SchemaSpy の紹介 -
 
PostgreSQL運用管理入門
PostgreSQL運用管理入門PostgreSQL運用管理入門
PostgreSQL運用管理入門
 
まずやっとくPostgreSQLチューニング
まずやっとくPostgreSQLチューニングまずやっとくPostgreSQLチューニング
まずやっとくPostgreSQLチューニング
 
[Postgre sql9.4新機能]レプリケーション・スロットの活用
[Postgre sql9.4新機能]レプリケーション・スロットの活用[Postgre sql9.4新機能]レプリケーション・スロットの活用
[Postgre sql9.4新機能]レプリケーション・スロットの活用
 
New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)
New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)
New features in ProxySQL 2.0 (updated to 2.0.9) by Rene Cannao (ProxySQL)
 
NGINX Installation and Tuning
NGINX Installation and TuningNGINX Installation and Tuning
NGINX Installation and Tuning
 

Andere mochten auch

Andere mochten auch (15)

An Introduction to Celery
An Introduction to CeleryAn Introduction to Celery
An Introduction to Celery
 
Django Celery - A distributed task queue
Django Celery - A distributed task queueDjango Celery - A distributed task queue
Django Celery - A distributed task queue
 
Distributed Task Processing with Celery - PyZH
Distributed Task Processing with Celery - PyZHDistributed Task Processing with Celery - PyZH
Distributed Task Processing with Celery - PyZH
 
Life in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with djangoLife in a Queue - Using Message Queue with django
Life in a Queue - Using Message Queue with django
 
Resftul API Web Development with Django Rest Framework & Celery
Resftul API Web Development with Django Rest Framework & CeleryResftul API Web Development with Django Rest Framework & Celery
Resftul API Web Development with Django Rest Framework & Celery
 
Building Distributed System with Celery on Docker Swarm - PyCon JP 2016
Building Distributed System with Celery on Docker Swarm - PyCon JP 2016Building Distributed System with Celery on Docker Swarm - PyCon JP 2016
Building Distributed System with Celery on Docker Swarm - PyCon JP 2016
 
Practical Celery
Practical CeleryPractical Celery
Practical Celery
 
Understanding Non Blocking I/O with Python
Understanding Non Blocking I/O with PythonUnderstanding Non Blocking I/O with Python
Understanding Non Blocking I/O with Python
 
Celery in the Django
Celery in the DjangoCelery in the Django
Celery in the Django
 
Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...
Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...
Website Monitoring with Distributed Messages/Tasks Processing (AMQP & RabbitM...
 
Advanced task management with Celery
Advanced task management with CeleryAdvanced task management with Celery
Advanced task management with Celery
 
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
 
Celery by dummy
Celery by dummyCelery by dummy
Celery by dummy
 
Scaling up task processing with Celery
Scaling up task processing with CeleryScaling up task processing with Celery
Scaling up task processing with Celery
 
Queue Everything and Please Everyone
Queue Everything and Please EveryoneQueue Everything and Please Everyone
Queue Everything and Please Everyone
 

Ähnlich wie Europython 2011 - Playing tasks with Django & Celery

Compatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsCompatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensions
Kai Cui
 
Django’s nasal passage
Django’s nasal passageDjango’s nasal passage
Django’s nasal passage
Erik Rose
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
Yehuda Katz
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
Yehuda Katz
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
Jacob Kaplan-Moss
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
Josh Mock
 

Ähnlich wie Europython 2011 - Playing tasks with Django & Celery (20)

Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
Compatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensionsCompatibility Detector Tool of Chrome extensions
Compatibility Detector Tool of Chrome extensions
 
Cross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App EngineCross Domain Web
Mashups with JQuery and Google App Engine
Cross Domain Web
Mashups with JQuery and Google App Engine
 
Тестирование и Django
Тестирование и DjangoТестирование и Django
Тестирование и Django
 
Animating angular applications
Animating angular applicationsAnimating angular applications
Animating angular applications
 
And the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack SupportAnd the Greatest of These Is ... Rack Support
And the Greatest of These Is ... Rack Support
 
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
 
Django’s nasal passage
Django’s nasal passageDjango’s nasal passage
Django’s nasal passage
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 
Ruby on Rails testing with Rspec
Ruby on Rails testing with RspecRuby on Rails testing with Rspec
Ruby on Rails testing with Rspec
 
Rails 3: Dashing to the Finish
Rails 3: Dashing to the FinishRails 3: Dashing to the Finish
Rails 3: Dashing to the Finish
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
JUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by exampleJUDCon London 2011 - Bin packing with drools planner by example
JUDCon London 2011 - Bin packing with drools planner by example
 
huhu
huhuhuhu
huhu
 
Testing Jboss Seam Bottom Up
Testing Jboss Seam Bottom UpTesting Jboss Seam Bottom Up
Testing Jboss Seam Bottom Up
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
The Best (and Worst) of Django
The Best (and Worst) of DjangoThe Best (and Worst) of Django
The Best (and Worst) of Django
 
JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
Unit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and NodeUnit testing JavaScript using Mocha and Node
Unit testing JavaScript using Mocha and Node
 
Painless Javascript Unit Testing
Painless Javascript Unit TestingPainless Javascript Unit Testing
Painless Javascript Unit Testing
 

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Europython 2011 - Playing tasks with Django & Celery

  • 1. Playing tasks with Django & Celery Mauro Rocco @fireantology
  • 2.
  • 5.
  • 7. celery contributor (just one of the hundreds )
  • 8.
  • 9. Statistics (downloads, listens, reviews, stars, fb likes) on different units
  • 10. Music analysis trough external services
  • 11. Music qualification trough several sources
  • 12. Integration with third part services
  • 13. Common jobs (contract generations, certifications, bills, search index update)
  • 14.
  • 20. Web monitoring (django-celery and others) “ Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well”
  • 21. AMPQ The Advanced Message Queuing Protocol (AMQP) is an open standard application layer protocol for Message Oriented Middleware.
  • 23.
  • 24. Can serve one or multiple queues
  • 25. Have a max number of tasks that can be executed at the same time
  • 26. Can be remotely controlled
  • 27. Have a great configuration option called MAX_TASK_PER_CHILD
  • 28.
  • 30. Defining a simple task from celery.decorators import task @task def make_money (how_much): logger = make_money.get_logger() logger.info( "Congratulation, you earned %s$" % how_much) if how_much>1000000: return "Bora Bora" return "Keep working" >>> result = make_money.delay(200) >>> result.get() “ Keep working”
  • 31. Retrying a task if something fails from celery.decorators import task @task def make_money_real_life (how_much, wife=True): try : logger = make_money.get_logger() if wife: raise Exception( "Incompatibility exception" ) logger.info( "Congratulation, you earned %s$" % how_much) if how_much>1000000: return "Bora Bora" return "Keep working" except Exception,exc: make_money_real_life.retry(exc=exc, countdown=60, args=[how_much,False])
  • 32. Task set example def run (self, setid=None, subtasks=None, **kwargs): … if not setid or not subtasks: … tasks = [] for slice in slices: tasks.append(uploadTrackSlice.subtask((slice,folder_name))) job = TaskSet(tasks=tasks) task_set_result = job.apply_async() setid = task_set_result.taskset_id subtasks = [result.task_id for result in task_set_result.subtasks] self.incrementalRetry("Result not ready", args=[setid,subtasks]) #Is a retry than we just have to check the results tasks_result = TaskSetResult(setid, map(AsyncResult,subtasks)) if not tasks_result.ready(): self.incrementalRetry( "Result not ready" , args=[setid,subtasks]) else : if tasks_result.successful(): return tasks_result.join() else : raise Exception( "Some of the tasks was failing" ) Extract from a jamendo task that upload track metadata in xml format to an ftp server for music analysis
  • 33. The Jamendo Task class class JamTask (Task): def __call__ (self, *args, **kwargs): """This method is in charge of call the run method of the task""" self.max_retries = 30 self.sandbox = SandBox(self.name, self.request.id, settings.PATH_SANDBOX, settings.DEBUG) self.taskLogger = TaskLogger(args, kwargs) self.taskLogger.__enter__() . . return self.run(*args, **kwargs) . . def after_return (self, status, retval, task_id, args, kwargs, einfo): """This method is called when the tasks end, on whatever return state""" self.taskLogger.__exit__(status, retval, args, kwargs, einfo) self.cleanTaskSandBox(status,kwargs) self.closeAllConnections() The way for define common behaviour to all your tasks is to override __call__ and after_return methods of the celery Task class
  • 34.
  • 37.
  • 38.
  • 39. django-celery settings.py INSTALLED_APPS += ("djcelery", ) . . import djcelery djcelery.setup_loader() . . CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler" . . #standard celery conf vars (Broker settings, concurrency ,...)
  • 43. Some little nice extensions Execute tasks directly from the django admin interface
  • 44. Some little nice extensions
  • 45.
  • 46. Atomic access to sensitive resources
  • 48. Define a list of UNIQUE tasks in settings.py
  • 49. If a lock is found define the behaviour retry or fail
  • 50. Allow the possibility of define a task UNIQUE on arguments (same task type with different arguments can run)
  • 51. Our solution : mongodb for write and release locks.
  • 52. Best solution: cache, virtual file system ?
  • 53. Unique tasks UNIQUE_TASKS = { "searchengines.solr.index": { "retry_on_lock": False, "lock_on_type": True, }, "stats.album.rebuild": { "retry_on_lock": True, "lock_on_type": False, }, } On task start ( method __call__ ) self.taskConcurrency = None if kwargs[ “task_name” ] in settings.UNIQUE_TASKS: self.taskConcurrency = TaskConcurrency(kwargs, args, settings.UNIQUE_TASKS[kwargs[ “task_name” ]]) if not self.taskConcurrency.canRun(): if self.taskConcurrency.retry: self.incrementalRetry(Exception( "Concurrency Exception" )) else : raise Exception( "Concurrency Exception" ) On task end ( method after_return ) if self.taskConcurrency: self.taskConcurrency.__exit__()
  • 54.
  • 55. Main Process logger, PoolWorker logger, TaskLogger
  • 56. The command logging.getLogger(“Celery”) give you back only the Main Process logger
  • 57. Extend logging features was a bit tricky until the last version
  • 58.
  • 59. after_setup_logger is triggered after the build of the Main Process logger and after the build of each PoolWorker logger
  • 60. The signals give you back a log object, in this way you can add additional handler for implement a centralized logging
  • 61. In our specific case we are sending the logs of all workers to a syslog server that store log lines in a separated file.
  • 62. Centralized logging import logging from celery.signals import after_setup_logger, after_setup_task_logger def after_setup_logger_handler (sender=None, logger=None, loglevel=None, logfile=None, format=None, colorize=None, **kwds): handler = logging.handlers.SysLogHandler(address=( 'syslogserver' , 514)) handler.setFormatter(logging.Formatter(format)) handler.setLevel(logging.INFO) logger.addHandler(handler) after_setup_logger.connect(after_setup_logger_handler) after_setup_task_logger.connect(after_setup_logger_handler)