Debian Codegraph @

docs/tutorials/task-cookbook.rst

raw
1 .. _cookbook-tasks:
2
3 ================
4 Task Cookbook
5 ================
6
7 .. contents::
8 :local:
9
10 .. _cookbook-task-serial:
11
12 Ensuring a task is only executed one at a time
13 ==============================================
14
15 You can accomplish this by using a lock.
16
17 In this example we'll be using the cache framework to set a lock that's
18 accessible for all workers.
19
20 It's part of an imaginary RSS feed importer called `djangofeeds`.
21 The task takes a feed URL as a single argument, and imports that feed into
22 a Django model called `Feed`. We ensure that it's not possible for two or
23 more workers to import the same feed at the same time by setting a cache key
24 consisting of the MD5 check-sum of the feed URL.
25
26 The cache key expires after some time in case something unexpected happens,
27 and something always will...
28
29 For this reason your tasks run-time shouldn't exceed the timeout.
30
31
32 .. note::
33
34 In order for this to work correctly you need to be using a cache
35 backend where the ``.add`` operation is atomic. ``memcached`` is known
36 to work well for this purpose.
37
38 .. code-block:: python
39
40 import time
41 from celery import task
42 from celery.utils.log import get_task_logger
43 from contextlib import contextmanager
44 from django.core.cache import cache
45 from hashlib import md5
46 from djangofeeds.models import Feed
47
48 logger = get_task_logger(__name__)
49
50 LOCK_EXPIRE = 60 * 10 # Lock expires in 10 minutes
51
52 @contextmanager
53 def memcache_lock(lock_id, oid):
54 timeout_at = time.monotonic() + LOCK_EXPIRE - 3
55 # cache.add fails if the key already exists
56 status = cache.add(lock_id, oid, LOCK_EXPIRE)
57 try:
58 yield status
59 finally:
60 # memcache delete is very slow, but we have to use it to take
61 # advantage of using add() for atomic locking
62 if time.monotonic() < timeout_at and status:
63 # don't release the lock if we exceeded the timeout
64 # to lessen the chance of releasing an expired lock
65 # owned by someone else
66 # also don't release the lock if we didn't acquire it
67 cache.delete(lock_id)
68
69 @task(bind=True)
70 def import_feed(self, feed_url):
71 # The cache key consists of the task name and the MD5 digest
72 # of the feed URL.
73 feed_url_hexdigest = md5(feed_url).hexdigest()
74 lock_id = '{0}-lock-{1}'.format(self.name, feed_url_hexdigest)
75 logger.debug('Importing feed: %s', feed_url)
76 with memcache_lock(lock_id, self.app.oid) as acquired:
77 if acquired:
78 return Feed.objects.import_feed(feed_url).url
79 logger.debug(
80 'Feed %s is already being imported by another worker', feed_url)