Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Q on asyncio
#4
(Jun-30-2024, 10:02 AM)ebolisa Wrote: I get a warning msg from pycharm stating "Coroutine 'create_task' is not awaited".
Never run Asynchronous/Concurrency in editors as they can block.

(Jun-30-2024, 12:20 PM)ebolisa Wrote: Thanks! It's not actually an error. It just highlights that line as a warning.
So, there's no need to "create a task" as shown in my test code?
Code from menator01 will not run in the background,it will run the get_temp coroutine in the foreground,and nothing else will happen concurrently.
For coroutine to run in the background while performing other tasks,as you use need asyncio.create_task().
To eg add like stop/break after 3-minutes.
import asyncio
from datetime import datetime, timedelta

async def temperatures(t, stop_event):
    while not stop_event.is_set():
        now = datetime.now()
        print(f'Displaying every 5 secs. {now:%S}')
        await asyncio.sleep(t)
    print("Stopping temperatures after 3 minutes")

async def main():
    stop_event = asyncio.Event()
    temperature_task = asyncio.create_task(temperatures(5, stop_event))
    start_time = datetime.now()
    while not stop_event.is_set():
        print('Clocking every second')
        await asyncio.sleep(1)
        if datetime.now() >= start_time + timedelta(minutes=3):
            stop_event.set()
    await temperature_task

def run():
    try:
        asyncio.run(main())
    except KeyboardInterrupt as err:
        print(f'kb interrupted {err}')

if __name__ == "__main__":
    run()
Reply


Messages In This Thread
Q on asyncio - by ebolisa - Jun-30-2024, 10:02 AM
RE: Q on asyncio - by menator01 - Jun-30-2024, 11:38 AM
RE: Q on asyncio - by ebolisa - Jun-30-2024, 12:20 PM
RE: Q on asyncio - by snippsat - Jun-30-2024, 04:06 PM
RE: Q on asyncio - by ebolisa - Jul-01-2024, 09:55 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020