Here's my take on this:
import asyncio
async def setInterval(callback, countdown):
async def job():
if countdown <= 0:
print('Countdown finished')
return
await asyncio.sleep(1)
callback(countdown)
await setInterval(callback, countdown-1)
await asyncio.ensure_future(job())
def myCallback(timeLeft):
print(f'Time left: {timeLeft}')
async def otherTask():
while True:
print('some other code running')
await asyncio.sleep(2)
async def main():
await asyncio.gather(
setInterval(myCallback, 10),
otherTask()
)
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(main())
The code above lets you trigger the function myCallback
every second, which you could use to display the time left to the users without blocking other code you might want to run while it is counting down.
Sample output is like:
some other code running
Time left: 10
some other code running
Time left: 9
Time left: 8
some other code running
Time left: 7
Time left: 6
some other code running
Time left: 5
Time left: 4
some other code running
Time left: 3
Time left: 2
some other code running
Time left: 1
Countdown finished
some other code running
some other code running
some other code running