Setting Time Limit on specific task with celery

jimstandard picture jimstandard · Jul 26, 2012 · Viewed 39.6k times · Source

I have a task in Celery that could potentially run for 10,000 seconds while operating normally. However all the rest of my tasks should be done in less than one second. How can I set a time limit for the intentionally long running task without changing the time limit on the short running tasks?

Answer

mher picture mher · Jul 26, 2012

You can set task time limits (hard and/or soft) either while defining a task or while calling.

from celery.exceptions import SoftTimeLimitExceeded

@celery.task(time_limit=20)
def mytask():
    try:
        return do_work()
    except SoftTimeLimitExceeded:
        cleanup_in_a_hurry()

or

mytask.apply_async(args=[], kwargs={}, time_limit=30, soft_time_limit=10)