task.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. """
  2. Working with tasks and task sets.
  3. """
  4. from carrot.connection import DjangoAMQPConnection
  5. from celery.messaging import TaskPublisher, TaskConsumer
  6. from celery.log import setup_logger
  7. from celery.registry import tasks
  8. from datetime import timedelta
  9. from celery.backends import default_backend
  10. from celery.result import AsyncResult, TaskSetResult
  11. import uuid
  12. import pickle
  13. def apply_async(task, args=None, kwargs=None, routing_key=None,
  14. immediate=None, mandatory=None, connection=None,
  15. connect_timeout=None, priority=None):
  16. """Run a task asynchronously by the celery daemon(s).
  17. :param task: The task to run (a callable object, or a :class:`Task`
  18. instance
  19. :param args: The positional arguments to pass on to the task (a ``list``).
  20. :param kwargs: The keyword arguments to pass on to the task (a ``dict``)
  21. :keyword routing_key: The routing key used to route the task to a worker
  22. server.
  23. :keyword immediate: Request immediate delivery. Will raise an exception
  24. if the task cannot be routed to a worker immediately.
  25. :keyword mandatory: Mandatory routing. Raises an exception if there's
  26. no running workers able to take on this task.
  27. :keyword connection: Re-use existing AMQP connection.
  28. The ``connect_timeout`` argument is not respected if this is set.
  29. :keyword connect_timeout: The timeout in seconds, before we give up
  30. on establishing a connection to the AMQP server.
  31. :keyword priority: The task priority, a number between ``0`` and ``9``.
  32. """
  33. if not args:
  34. args = []
  35. if not kwargs:
  36. kwargs = []
  37. message_opts = {"routing_key": routing_key,
  38. "immediate": immediate,
  39. "mandatory": mandatory,
  40. "priority": priority}
  41. for option_name, option_value in message_opts.items():
  42. message_opts[option_name] = getattr(task, option_name, option_value)
  43. need_to_close_connection = False
  44. if not connection:
  45. connection = DjangoAMQPConnection(connect_timeout=connect_timeout)
  46. need_to_close_connection = True
  47. publisher = TaskPublisher(connection=connection)
  48. task_id = publisher.delay_task(task.name, args, kwargs, **message_opts)
  49. publisher.close()
  50. if need_to_close_connection:
  51. connection.close()
  52. return AsyncResult(task_id)
  53. def delay_task(task_name, *args, **kwargs):
  54. """Delay a task for execution by the ``celery`` daemon.
  55. :param task_name: the name of a task registered in the task registry.
  56. :param \*args: positional arguments to pass on to the task.
  57. :param \*\*kwargs: keyword arguments to pass on to the task.
  58. :raises celery.registry.NotRegistered: exception if no such task
  59. has been registered in the task registry.
  60. :rtype: :class:`celery.result.AsyncResult`.
  61. Example
  62. >>> r = delay_task("update_record", name="George Constanza", age=32)
  63. >>> r.ready()
  64. True
  65. >>> r.result
  66. "Record was updated"
  67. """
  68. if task_name not in tasks:
  69. raise tasks.NotRegistered(
  70. "Task with name %s not registered in the task registry." % (
  71. task_name))
  72. task = tasks[task_name]
  73. return apply_async(task, args, kwargs)
  74. def discard_all():
  75. """Discard all waiting tasks.
  76. This will ignore all tasks waiting for execution, and they will
  77. be deleted from the messaging server.
  78. :returns: the number of tasks discarded.
  79. :rtype: int
  80. """
  81. amqp_connection = DjangoAMQPConnection()
  82. consumer = TaskConsumer(connection=amqp_connection)
  83. discarded_count = consumer.discard_all()
  84. amqp_connection.close()
  85. return discarded_count
  86. def is_done(task_id):
  87. """Returns ``True`` if task with ``task_id`` has been executed.
  88. :rtype: bool
  89. """
  90. return default_backend.is_done(task_id)
  91. class Task(object):
  92. """A task that can be delayed for execution by the ``celery`` daemon.
  93. All subclasses of :class:`Task` must define the :meth:`run` method,
  94. which is the actual method the ``celery`` daemon executes.
  95. The :meth:`run` method supports both positional, and keyword arguments.
  96. .. attribute:: name
  97. *REQUIRED* All subclasses of :class:`Task` has to define the
  98. :attr:`name` attribute. This is the name of the task, registered
  99. in the task registry, and passed to :func:`delay_task`.
  100. .. attribute:: type
  101. The type of task, currently this can be ``regular``, or ``periodic``,
  102. however if you want a periodic task, you should subclass
  103. :class:`PeriodicTask` instead.
  104. :raises NotImplementedError: if the :attr:`name` attribute is not set.
  105. The resulting class is callable, which if called will apply the
  106. :meth:`run` method.
  107. Examples
  108. This is a simple task just logging a message,
  109. >>> from celery.task import tasks, Task
  110. >>> class MyTask(Task):
  111. ... name = "mytask"
  112. ...
  113. ... def run(self, some_arg=None, **kwargs):
  114. ... logger = self.get_logger(**kwargs)
  115. ... logger.info("Running MyTask with arg some_arg=%s" %
  116. ... some_arg))
  117. ... return 42
  118. ... tasks.register(MyTask)
  119. You can delay the task using the classmethod :meth:`delay`...
  120. >>> result = MyTask.delay(some_arg="foo")
  121. >>> result.status # after some time
  122. 'DONE'
  123. >>> result.result
  124. 42
  125. ...or using the :func:`delay_task` function, by passing the name of
  126. the task.
  127. >>> from celery.task import delay_task
  128. >>> result = delay_task(MyTask.name, some_arg="foo")
  129. """
  130. name = None
  131. type = "regular"
  132. max_retries = 0 # unlimited
  133. retry_interval = timedelta(seconds=2)
  134. auto_retry = False
  135. routing_key = None
  136. immediate = False
  137. mandatory = False
  138. def __init__(self):
  139. if not self.name:
  140. raise NotImplementedError("Tasks must define a name attribute.")
  141. def __call__(self, *args, **kwargs):
  142. return self.run(*args, **kwargs)
  143. def run(self, *args, **kwargs):
  144. """*REQUIRED* The actual task.
  145. All subclasses of :class:`Task` must define the run method.
  146. :raises NotImplementedError: by default, so you have to override
  147. this method in your subclass.
  148. """
  149. raise NotImplementedError("Tasks must define a run method.")
  150. def get_logger(self, **kwargs):
  151. """Get process-aware logger object.
  152. See :func:`celery.log.setup_logger`.
  153. """
  154. return setup_logger(**kwargs)
  155. def get_publisher(self):
  156. """Get a celery task message publisher.
  157. :rtype: :class:`celery.messaging.TaskPublisher`.
  158. Please be sure to close the AMQP connection when you're done
  159. with this object, i.e.:
  160. >>> publisher = self.get_publisher()
  161. >>> # do something with publisher
  162. >>> publisher.connection.close()
  163. """
  164. return TaskPublisher(connection=DjangoAMQPConnection())
  165. def get_consumer(self):
  166. """Get a celery task message consumer.
  167. :rtype: :class:`celery.messaging.TaskConsumer`.
  168. Please be sure to close the AMQP connection when you're done
  169. with this object. i.e.:
  170. >>> consumer = self.get_consumer()
  171. >>> # do something with consumer
  172. >>> consumer.connection.close()
  173. """
  174. return TaskConsumer(connection=DjangoAMQPConnection())
  175. @classmethod
  176. def delay(cls, *args, **kwargs):
  177. """Delay this task for execution by the ``celery`` daemon(s).
  178. :param \*args: positional arguments passed on to the task.
  179. :param \*\*kwargs: keyword arguments passed on to the task.
  180. :rtype: :class:`celery.result.AsyncResult`
  181. See :func:`delay_task`.
  182. """
  183. return apply_async(cls, args, kwargs)
  184. @classmethod
  185. def apply_async(cls, args=None, kwargs=None, **options):
  186. """Delay this task for execution by the ``celery`` daemon(s).
  187. :param args: positional arguments passed on to the task.
  188. :param kwargs: keyword arguments passed on to the task.
  189. :rtype: :class:`celery.result.AsyncResult`
  190. See :func:`apply_async`.
  191. """
  192. return apply_async(cls, args, kwargs, **options)
  193. class TaskSet(object):
  194. """A task containing several subtasks, making it possible
  195. to track how many, or when all of the tasks has been completed.
  196. :param task: The task class or name.
  197. Can either be a fully qualified task name, or a task class.
  198. :param args: A list of args, kwargs pairs.
  199. e.g. ``[[args1, kwargs1], [args2, kwargs2], ..., [argsN, kwargsN]]``
  200. .. attribute:: task_name
  201. The name of the task.
  202. .. attribute:: arguments
  203. The arguments, as passed to the task set constructor.
  204. .. attribute:: total
  205. Total number of tasks in this task set.
  206. Example
  207. >>> from djangofeeds.tasks import RefreshFeedTask
  208. >>> taskset = TaskSet(RefreshFeedTask, args=[
  209. ... [], {"feed_url": "http://cnn.com/rss"},
  210. ... [], {"feed_url": "http://bbc.com/rss"},
  211. ... [], {"feed_url": "http://xkcd.com/rss"}])
  212. >>> taskset_result = taskset.run()
  213. >>> list_of_return_values = taskset.join()
  214. """
  215. def __init__(self, task, args):
  216. try:
  217. task_name = task.name
  218. except AttributeError:
  219. task_name = task
  220. self.task_name = task_name
  221. self.arguments = args
  222. self.total = len(args)
  223. def run(self):
  224. """Run all tasks in the taskset.
  225. :returns: A :class:`celery.result.TaskSetResult` instance.
  226. Example
  227. >>> ts = TaskSet(RefreshFeedTask, [
  228. ... ["http://foo.com/rss", {}],
  229. ... ["http://bar.com/rss", {}],
  230. ... )
  231. >>> result = ts.run()
  232. >>> result.taskset_id
  233. "d2c9b261-8eff-4bfb-8459-1e1b72063514"
  234. >>> result.subtask_ids
  235. ["b4996460-d959-49c8-aeb9-39c530dcde25",
  236. "598d2d18-ab86-45ca-8b4f-0779f5d6a3cb"]
  237. >>> result.waiting()
  238. True
  239. >>> time.sleep(10)
  240. >>> result.ready()
  241. True
  242. >>> result.successful()
  243. True
  244. >>> result.failed()
  245. False
  246. >>> result.join()
  247. [True, True]
  248. """
  249. taskset_id = str(uuid.uuid4())
  250. conn = DjangoAMQPConnection()
  251. publisher = TaskPublisher(connection=conn)
  252. subtask_ids = [publisher.delay_task_in_set(task_name=self.task_name,
  253. taskset_id=taskset_id,
  254. task_args=arg,
  255. task_kwargs=kwarg)
  256. for arg, kwarg in self.arguments]
  257. publisher.close()
  258. conn.close()
  259. return TaskSetResult(taskset_id, subtask_ids)
  260. def iterate(self):
  261. """Iterate over the results returned after calling :meth:`run`.
  262. If any of the tasks raises an exception, the exception will
  263. be re-raised.
  264. """
  265. return iter(self.run())
  266. def join(self, timeout=None):
  267. """Gather the results for all of the tasks in the taskset,
  268. and return a list with them ordered by the order of which they
  269. were called.
  270. :keyword timeout: The time in seconds, how long
  271. it will wait for results, before the operation times out.
  272. :raises celery.timer.TimeoutError: if ``timeout`` is not ``None``
  273. and the operation takes longer than ``timeout`` seconds.
  274. If any of the tasks raises an exception, the exception
  275. will be reraised by :meth:`join`.
  276. :returns: list of return values for all tasks in the taskset.
  277. """
  278. return self.run().join(timeout=timeout)
  279. @classmethod
  280. def remote_execute(cls, func, args):
  281. """Apply ``args`` to function by distributing the args to the
  282. celery server(s)."""
  283. pickled = pickle.dumps(func)
  284. arguments = [[[pickled, arg, {}], {}] for arg in args]
  285. return cls(ExecuteRemoteTask, arguments)
  286. @classmethod
  287. def map(cls, func, args, timeout=None):
  288. """Distribute processing of the arguments and collect the results."""
  289. remote_task = cls.remote_execute(func, args)
  290. return remote_task.join(timeout=timeout)
  291. @classmethod
  292. def map_async(cls, func, args, timeout=None):
  293. """Distribute processing of the arguments and collect the results
  294. asynchronously.
  295. :returns: :class:`celery.result.AsyncResult` instance.
  296. """
  297. serfunc = pickle.dumps(func)
  298. return AsynchronousMapTask.delay(serfunc, args, timeout=timeout)
  299. def dmap(func, args, timeout=None):
  300. """Distribute processing of the arguments and collect the results.
  301. Example
  302. >>> from celery.task import map
  303. >>> import operator
  304. >>> dmap(operator.add, [[2, 2], [4, 4], [8, 8]])
  305. [4, 8, 16]
  306. """
  307. return TaskSet.map(func, args, timeout=timeout)
  308. class AsynchronousMapTask(Task):
  309. """Task used internally by :func:`dmap_async` and
  310. :meth:`TaskSet.map_async`. """
  311. name = "celery.map_async"
  312. def run(self, serfunc, args, **kwargs):
  313. """The method run by ``celeryd``."""
  314. timeout = kwargs.get("timeout")
  315. return TaskSet.map(pickle.loads(serfunc), args, timeout=timeout)
  316. tasks.register(AsynchronousMapTask)
  317. def dmap_async(func, args, timeout=None):
  318. """Distribute processing of the arguments and collect the results
  319. asynchronously.
  320. :returns: :class:`celery.result.AsyncResult` object.
  321. Example
  322. >>> from celery.task import dmap_async
  323. >>> import operator
  324. >>> presult = dmap_async(operator.add, [[2, 2], [4, 4], [8, 8]])
  325. >>> presult
  326. <AsyncResult: 373550e8-b9a0-4666-bc61-ace01fa4f91d>
  327. >>> presult.status
  328. 'DONE'
  329. >>> presult.result
  330. [4, 8, 16]
  331. """
  332. return TaskSet.map_async(func, args, timeout=timeout)
  333. class PeriodicTask(Task):
  334. """A periodic task is a task that behaves like a :manpage:`cron` job.
  335. .. attribute:: run_every
  336. *REQUIRED* Defines how often the task is run (its interval),
  337. it can be either a :class:`datetime.timedelta` object or an
  338. integer specifying the time in seconds.
  339. :raises NotImplementedError: if the :attr:`run_every` attribute is
  340. not defined.
  341. You have to register the periodic task in the task registry.
  342. Example
  343. >>> from celery.task import tasks, PeriodicTask
  344. >>> from datetime import timedelta
  345. >>> class MyPeriodicTask(PeriodicTask):
  346. ... name = "my_periodic_task"
  347. ... run_every = timedelta(seconds=30)
  348. ...
  349. ... def run(self, **kwargs):
  350. ... logger = self.get_logger(**kwargs)
  351. ... logger.info("Running MyPeriodicTask")
  352. >>> tasks.register(MyPeriodicTask)
  353. """
  354. run_every = timedelta(days=1)
  355. type = "periodic"
  356. def __init__(self):
  357. if not self.run_every:
  358. raise NotImplementedError(
  359. "Periodic tasks must have a run_every attribute")
  360. # If run_every is a integer, convert it to timedelta seconds.
  361. if isinstance(self.run_every, int):
  362. self.run_every = timedelta(seconds=self.run_every)
  363. super(PeriodicTask, self).__init__()
  364. class ExecuteRemoteTask(Task):
  365. """Execute an arbitrary function or object.
  366. *Note* You probably want :func:`execute_remote` instead, which this
  367. is an internal component of.
  368. The object must be pickleable, so you can't use lambdas or functions
  369. defined in the REPL (that is the python shell, or ``ipython``).
  370. """
  371. name = "celery.execute_remote"
  372. def run(self, ser_callable, fargs, fkwargs, **kwargs):
  373. """
  374. :param ser_callable: A pickled function or callable object.
  375. :param fargs: Positional arguments to apply to the function.
  376. :param fkwargs: Keyword arguments to apply to the function.
  377. """
  378. callable_ = pickle.loads(ser_callable)
  379. return callable_(*fargs, **fkwargs)
  380. tasks.register(ExecuteRemoteTask)
  381. def execute_remote(func, *args, **kwargs):
  382. """Execute arbitrary function/object remotely.
  383. :param func: A callable function or object.
  384. :param \*args: Positional arguments to apply to the function.
  385. :param \*\*kwargs: Keyword arguments to apply to the function.
  386. The object must be picklable, so you can't use lambdas or functions
  387. defined in the REPL (the objects must have an associated module).
  388. :returns: class:`celery.result.AsyncResult`.
  389. """
  390. return ExecuteRemoteTask.delay(pickle.dumps(func), args, kwargs)
  391. class DeleteExpiredTaskMetaTask(PeriodicTask):
  392. """A periodic task that deletes expired task metadata every day.
  393. This runs the current backend's
  394. :meth:`celery.backends.base.BaseBackend.cleanup` method.
  395. """
  396. name = "celery.delete_expired_task_meta"
  397. run_every = timedelta(days=1)
  398. def run(self, **kwargs):
  399. """The method run by ``celeryd``."""
  400. logger = self.get_logger(**kwargs)
  401. logger.info("Deleting expired task meta objects...")
  402. default_backend.cleanup()
  403. tasks.register(DeleteExpiredTaskMetaTask)