timer examples

This commit is contained in:
Luciano Ramalho 2015-01-18 16:55:23 -02:00
parent dc0cfa11e1
commit ca0566df16
3 changed files with 72 additions and 0 deletions

19
concurrency/timer.py Normal file
View File

@ -0,0 +1,19 @@
import asyncio
@asyncio.coroutine
def show_remaining():
remaining = 5
while remaining:
print('Remaining: ', remaining)
yield from asyncio.sleep(1)
remaining -= 1
def main():
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(show_remaining())
finally:
loop.close()
if __name__ == '__main__':
main()

30
concurrency/timer2.py Normal file
View File

@ -0,0 +1,30 @@
import asyncio
import sys
import contextlib
@asyncio.coroutine
def show_remaining(dots_task):
remaining = 5
while remaining:
print('Remaining: ', remaining)
sys.stdout.flush()
yield from asyncio.sleep(1)
remaining -= 1
dots_task.cancel()
print()
@asyncio.coroutine
def dots():
while True:
print('.', sep='', end='')
sys.stdout.flush()
yield from asyncio.sleep(.1)
def main():
with contextlib.closing(asyncio.get_event_loop()) as loop:
dots_task = asyncio.Task(dots())
coros = [show_remaining(dots_task), dots_task]
loop.run_until_complete(asyncio.wait(coros))
if __name__ == '__main__':
main()

23
concurrency/timer_cb.py Normal file
View File

@ -0,0 +1,23 @@
import asyncio
def show_remaining(loop):
if not hasattr(show_remaining, 'remaining'):
show_remaining.remaining = 5
print('Remaining: ', show_remaining.remaining)
show_remaining.remaining -= 1
if show_remaining.remaining:
loop.call_later(1, show_remaining, loop)
else:
loop.stop()
def main():
loop = asyncio.get_event_loop()
try:
loop.call_soon(show_remaining, loop)
loop.run_forever()
finally:
loop.close()
if __name__ == '__main__':
main()