3

Do you think it is possible to use asyncio to run a task every n seconds in django, so that the main process wouldn't be blocked?

Something for example that would print every 5 min in console, like:

 import asyncio from random import randint async def do_stuff(something, howmany): for i in range(howmany): print('We are doing {}'.format(something)) await asyncio.sleep(randint(0, 5)) if __name__ == '__main__': loop = asyncio.get_event_loop() work = [ asyncio.ensure_future(do_stuff('something', 5)), ] loop.run_until_complete(asyncio.gather(*work)) 

It seems that django will stop working while the loop is running. Even if this can be made to work in development, how would it behave when the site goes live on something like apache or gunicorn?

1
  • Maybe use multiprocessing would be an alternative? Commented May 8, 2017 at 2:47

1 Answer 1

7

While it would be possible to achieve this with a lot of hard work. Much simpler is to use the time honoured practice of using a cron job. See this: Using django for CLI tool

Nowadays a more popular approach (among django devs at any rate) is to use celery. Specifically celery beat

celery beat is a scheduler; It kicks off tasks at regular intervals, that are then executed by available worker nodes in the cluster.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.