tasks.rst 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. ================
  2. Creating Tasks
  3. ================
  4. Ensuring a task is only executed one at a time
  5. ----------------------------------------------
  6. You can accomplish this by using a lock.
  7. In this example we'll be using the cache framework to set a lock that is
  8. accessible for all workers.
  9. It's part of an imaginary RSS feed importer called ``djangofeeds``.
  10. The task takes a feed URL as a single argument, and imports that feed into
  11. a Django model called ``Feed``. We ensure that it's not possible for two or
  12. more workers to import the same feed at the same time by setting a cache key
  13. consisting of the md5sum of the feed URL.
  14. The cache key expires after some time in case something unexpected happens
  15. (you never know, right?)
  16. .. code-block:: python
  17. from celery.task import Task
  18. from django.core.cache import cache
  19. from django.utils.hashcompat import md5_constructor as md5
  20. from djangofeeds.models import Feed
  21. LOCK_EXPIRE = 60 * 5 # Lock expires in 5 minutes
  22. class FeedImporter(Task):
  23. name = "feed.import"
  24. def run(self, feed_url, **kwargs):
  25. logger = self.get_logger(**kwargs)
  26. # The cache key consists of the task name and the MD5 digest
  27. # of the feed URL.
  28. feed_url_digest = md5(feed_url).hexdigest()
  29. lock_id = "%s-lock-%s" % (self.name, feed_url_hexdigest)
  30. # cache.add fails if if the key already exists
  31. acquire_lock = lambda: cache.add(lock_id, "true", LOCK_EXPIRE)
  32. # memcache delete is very slow, but we have to use it to take
  33. # advantage of using add() for atomic locking
  34. release_lock = lambda: cache.delete(lock_id)
  35. logger.debug("Importing feed: %s" % feed_url)
  36. if aquire_lock():
  37. try:
  38. feed = Feed.objects.import_feed(feed_url)
  39. finally:
  40. release_lock()
  41. return feed.url
  42. logger.debug(
  43. "Feed %s is already being imported by another worker" % (
  44. feed_url))
  45. return