Skip to content

Commit ca0566d

Browse files
committed
timer examples
1 parent dc0cfa1 commit ca0566d

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed

concurrency/timer.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import asyncio
2+
3+
@asyncio.coroutine
4+
def show_remaining():
5+
remaining = 5
6+
while remaining:
7+
print('Remaining: ', remaining)
8+
yield from asyncio.sleep(1)
9+
remaining -= 1
10+
11+
def main():
12+
loop = asyncio.get_event_loop()
13+
try:
14+
loop.run_until_complete(show_remaining())
15+
finally:
16+
loop.close()
17+
18+
if __name__ == '__main__':
19+
main()

concurrency/timer2.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import asyncio
2+
import sys
3+
import contextlib
4+
5+
@asyncio.coroutine
6+
def show_remaining(dots_task):
7+
remaining = 5
8+
while remaining:
9+
print('Remaining: ', remaining)
10+
sys.stdout.flush()
11+
yield from asyncio.sleep(1)
12+
remaining -= 1
13+
dots_task.cancel()
14+
print()
15+
16+
@asyncio.coroutine
17+
def dots():
18+
while True:
19+
print('.', sep='', end='')
20+
sys.stdout.flush()
21+
yield from asyncio.sleep(.1)
22+
23+
def main():
24+
with contextlib.closing(asyncio.get_event_loop()) as loop:
25+
dots_task = asyncio.Task(dots())
26+
coros = [show_remaining(dots_task), dots_task]
27+
loop.run_until_complete(asyncio.wait(coros))
28+
29+
if __name__ == '__main__':
30+
main()

concurrency/timer_cb.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import asyncio
2+
3+
def show_remaining(loop):
4+
if not hasattr(show_remaining, 'remaining'):
5+
show_remaining.remaining = 5
6+
7+
print('Remaining: ', show_remaining.remaining)
8+
show_remaining.remaining -= 1
9+
if show_remaining.remaining:
10+
loop.call_later(1, show_remaining, loop)
11+
else:
12+
loop.stop()
13+
14+
def main():
15+
loop = asyncio.get_event_loop()
16+
try:
17+
loop.call_soon(show_remaining, loop)
18+
loop.run_forever()
19+
finally:
20+
loop.close()
21+
22+
if __name__ == '__main__':
23+
main()

0 commit comments

Comments
 (0)