Created
January 3, 2017 18:07
-
-
Save fabiocerqueira/55761ba8388e20be4e441e1d73609c36 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import asyncio | |
| from collections import namedtuple | |
| from functools import wraps | |
| tasks = [] | |
| loop = asyncio.get_event_loop() | |
| PeriodicTask = namedtuple('PeriodicTask', ['task', 'interval', 'start']) | |
| def periodic(interval, start=False): | |
| def internal_periodic(coro): | |
| tasks.append(PeriodicTask(task=coro, interval=interval, start=start)) | |
| return coro | |
| return internal_periodic | |
| async def periodic_runner(period_task): | |
| if period_task.start: | |
| asyncio.ensure_future(period_task.task()) | |
| while True: | |
| await asyncio.sleep(period_task.interval) | |
| asyncio.ensure_future(period_task.task()) | |
| @periodic(10, start=True) | |
| async def task_blocking(): | |
| print('[1] task blocking', loop.time()) | |
| await asyncio.sleep(10) | |
| print('[1] task blocking end', loop.time()) | |
| @periodic(5) | |
| async def task_blocking2(): | |
| print('[2] task blocking', loop.time()) | |
| await asyncio.sleep(3) | |
| print('[2] task blocking end', loop.time()) | |
| if __name__ == '__main__': | |
| for t in tasks: | |
| asyncio.ensure_future(periodic_runner(t)) | |
| try: | |
| loop.run_forever() | |
| finally: | |
| loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment