tasks.rst 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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.
  8. It's part of an imaginary RSS Feed application called ``djangofeeds``.
  9. The task takes a feed URL as a single argument, and imports that feed into
  10. a Django model called ``Feed``. We ensure that it's not possible for two or
  11. more workers to import the same feed at the same time by setting a cache key
  12. consisting of the md5sum of the feed URL.
  13. The cache key expires after some time in case something unexpected happens
  14. (you never know, right?)
  15. .. code-block:: python
  16. from celery.task import Task
  17. from celery.registry import tasks
  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. is_locked = lambda: str(cache.get(lock_id)) == "true"
  31. acquire_lock = lambda: cache.set(lock_id, "true", LOCK_EXPIRE)
  32. # memcache delete is very slow, so we'd rather set a false value
  33. # with a very low expiry time.
  34. release_lock = lambda: cache.set(lock_id, "nil", 1)
  35. logger.debug("Importing feed: %s" % feed_url)
  36. if is_locked():
  37. logger.debug(
  38. "Feed %s is already being imported by another worker" % (
  39. feed_url))
  40. return
  41. acquire_lock()
  42. try:
  43. feed = Feed.objects.import(feed_url)
  44. finally:
  45. release_lock()
  46. return feed.url
  47. tasks.register(FeedImporter)