Event Loop

Python SELF EN
Level 25 , Lesson 5
Available

6.1 Getting the Event Loop

The Event Loop is the central component in asynchronous programming using the asyncio module in Python. It manages the execution of asynchronous tasks, event handling, and input-output operations. The event loop allows multiple tasks to run simultaneously without blocking the main execution thread.

Creating and Getting the Event Loop

  • asyncio.get_event_loop(): Returns the current event loop or creates a new one if there isn't one.
  • asyncio.new_event_loop(): Creates a new event loop.
  • asyncio.set_event_loop(loop): Sets the specified event loop as the current one.

Example:

asyncio has a current event loop that contains all the running tasks. You can get the current event loop or create a new one and set it as the current. This is shown in the example below.


import asyncio

loop = asyncio.get_event_loop()
print(loop)  # Current event loop
new_loop = asyncio.new_event_loop()
asyncio.set_event_loop(new_loop)
print(asyncio.get_event_loop())  # New set event loop

It's worth noting that the get_event_loop() method returns the current active event loop. Creating a new event loop and setting it should be done with caution to avoid conflicts in asynchronous applications.

Running the Event Loop

  • run_forever(): Runs the event loop and continues its execution until stop() is called.
  • run_until_complete(future): Runs the event loop and completes it after the given coroutine or future object is finished.

Example:

The event loop can run in two modes: run indefinitely — kind of like while True, or until a specific task is complete.


import asyncio

async def hello():
    print("Hello")
    await asyncio.sleep(1)
    print("World")
            
loop = asyncio.get_event_loop()
loop.run_until_complete(hello())
loop.close()

If you started the Event Loop in run_forever() mode, it will keep looping indefinitely. The run_forever() method will stop only if some asynchronous task calls the stop() method on our EventLoop.

Stopping the Event Loop

  • stop(): Stops the event loop.
  • is_running(): Returns True if the event loop is running.

Example:

If the loop is running in infinite mode, it constantly receives and executes tasks; it won't stop by itself. Someone needs to get the object of our current loop and call the stop() method on it. To check if the loop is running infinitely, call the is_running() method.


import asyncio
            
loop = asyncio.get_event_loop()
loop.stop()
print(loop.is_running())  # False

6.2 Important Methods of the Event Loop

Method call_soon(callback, *args)

Schedules the callback function with arguments *args to be called as soon as possible.


import asyncio

def my_callback():
    print("Callback executed")
            
loop = asyncio.get_event_loop()
loop.call_soon(my_callback)
loop.run_forever()

Puts the callback function at the very front of the task list so it starts executing as soon as possible. Non-asynchronous functions can be passed to this method. This method is useful when you need to execute a task with minimal delay, especially when a prompt response is required in an asynchronous application.

Method call_later(delay, callback, *args)

Schedules the callback function with arguments *args to be called after delay seconds.


import asyncio

def my_callback():
    print("Callback executed after delay")
            
loop = asyncio.get_event_loop()
loop.call_later(2, my_callback)
loop.run_forever()

This method allows you to execute a delayed function call: the first parameter is the delay in seconds (can be fractional), followed by a reference to the function and its parameters. Non-asynchronous functions can be passed to this method. This method can be used to manage the execution of tasks with varying urgency levels, which is useful when designing complex asynchronous systems.

Method call_at(when, callback, *args)

Schedules the callback function with arguments *args to be called at the time when.


import asyncio
import time
            
def my_callback():
    print("Callback executed at specific time")
            
loop = asyncio.get_event_loop()
when = loop.time() + 2  # In 2 seconds from the current event loop time
loop.call_at(when, my_callback)
loop.run_forever()

If you want to run a task not in 5 seconds, but for example, at 3:00 PM or midnight, it would be more convenient to use the call_at() function, which works just like the call_soon() function, but the first parameter is the time at which the function should be called. Non-asynchronous functions can be passed to this method.

Advantages and Features

Asynchronous Execution: The event loop allows multiple tasks to run concurrently without blocking the main execution thread.

Efficient Resource Management: Asynchronous input-output operations are executed without blocking, making programs more efficient.

Flexibility and Scalability: The event loop supports a variety of methods for scheduling tasks and handling events, allowing for the creation of complex and scalable asynchronous applications.

6.3 Interacting with Tasks and Future Objects

The event loop manages the execution of Tasks and Futures. It tracks their state and ensures they are executed as they become ready.

Example:


import asyncio

async def main():
    await asyncio.sleep(1)
    print("Task completed")
            
loop = asyncio.get_event_loop()
task = loop.create_task(main())
loop.run_until_complete(task)

This example shows how the event loop manages the execution of a task created using the create_task method. Methods like call_soon(), call_later(), and call_at() can be used to control the execution of tasks with different levels of urgency, which is useful when designing complex asynchronous systems.

2
Task
Python SELF EN, level 25, lesson 5
Locked
Creating and obtaining an event loop
Creating and obtaining an event loop
2
Task
Python SELF EN, level 25, lesson 5
Locked
Starting and Stopping the Event Loop
Starting and Stopping the Event Loop
1
Опрос
Multithreading,  25 уровень,  5 лекция
недоступен
Multithreading
Multithreading
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION