Combining a Deadline and an Operator Stop
In this lesson, you give a station poll a deadline as well as a stop button, and make one signal carry both. A hung poll shouldn’t hold the dashboard forever, so Ridge gets 250 milliseconds; each reading takes 100.
In Python, asyncio.timeout() puts the deadline around the await. The poll closes its station
link in a finally block; the print() stands in for a real connection:
import asyncio
async def poll_station(name, samples):
try:
for sample in samples:
reading = await asyncio.sleep(0.1, result=sample)
print(name, "reading", reading)
print(name, "poll finished")
finally:
print(name, "link closed")
async def main():
try:
async with asyncio.timeout(0.25):
await poll_station("Ridge", [8, 12, 10])
except TimeoutError as error:
print("name:", type(error).__name__)
asyncio.run(main())
The log shows two readings, link closed, then the TimeoutError that main() caught:
Ridge reading 8
Ridge reading 12
Ridge link closed
name: TimeoutError