coroutine, asyncio, yield
import time
from datetime import datetime
import asyncio
#@ coroutine by yield
def print_message_periodical1(interval_seconds, message='keep alive'):
while True:
print(f'{datetime.now()}-{message}')
start=time.time()
end=start+interval_seconds
while True:
yield
now=time.time()
if now>=end:
break
def coroutine_by_yield():
a=print_message_periodical1(1, 'one')
b=print_message_periodical1(3, 'three')
stack=[a,b]
while True:
for task in stack:
next(task)
#@ coroutine by asyncio
async def print_message_periodical2(interval_seconds,message='keep alive'):
while True:
print(f'{datetime.now()}-{message}')
start = time.time()
end = start + interval_seconds
while True:
await asyncio.sleep(0)
now = time.time()
if now >= end:
break
def coroutine_by_asyncio():
scheduler=asyncio.get_event_loop()
scheduler.create_task(print_message_periodical2(1,'one'))
scheduler.create_task(print_message_periodical2(3,'three'))
scheduler.run_forever()
if __name__ == '__main__':
coroutine_by_yield()
coroutine_by_asyncio()