How to execute a function asynchronously every 60 seconds in Python?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Asynchronous programming in Python has become increasingly popular due to its non-blocking nature, allowing developers to handle I/O-bound tasks efficiently. One common use case is executing a function asynchronously at a regular interval, such as every 60 seconds. This task can be achieved using Python's asyncio library, which offers efficient ways to handle asynchronous I/O.
Overview of Asynchronous Programming
Before diving into the implementation, it's crucial to understand what asynchronous programming means. Unlike synchronous programming, where tasks are performed one after the other, asynchronous programming allows tasks to be run concurrently. This concurrency is especially useful when one task is waiting for I/O operations to complete, enabling another task to proceed.
The asyncio library is Python’s built-in library for writing single-threaded concurrent code using coroutines. A coroutine is a special function that can yield control back to the event loop, allowing other operations to execute during I/O waits.
Core Concepts
- Event Loop: The heart of
asyncio, responsible for executing asynchronous tasks. It schedules and runs coroutines, ensuring they are executed at appropriate times. - Coroutine: A function defined with
async def, which can be awaited. It containsawaitexpressions to pause execution and yield control for other operations. - Task: A wrapper for executing a coroutine, allowing it to be scheduled on the event loop.
Sample Implementation
Here's a step-by-step guide on setting up an asynchronous function that runs every 60 seconds.
Step 1: Import Required Modules
First, import asyncio for handling asynchronous tasks and time to provide the current timestamp when needed.
Step 2: Define the Asynchronous Function
Define your function using async def, allowing you to leverage await to pause and resume the coroutine as needed.
Step 3: Create a Repeating Task
Define another asynchronous function to schedule the repeating task. This function will include an infinite loop, ensuring that the function is executed every 60 seconds.
Step 4: Run the Event Loop
Finally, initialize the event loop and schedule the repeating task.
Explanation
async def my_task(): Defines an asynchronous function that performs the task. It usesawait asyncio.sleep(2)to simulate work.repeat_task(interval): Continuously runsmy_task()followed by a sleep period equal to the specified interval (60 seconds).loop.run_until_complete(): Starts the event loop to runrepeat_task()until it’s terminated (e.g., with a keyboard interrupt).
Table Summary
| Concept | Description |
| Asynchronous | Non-blocking, concurrent code execution using coroutines. |
| Event Loop | Central component running tasks and managing coroutines. |
| Coroutine | Function that can be paused and resumed using await. |
| Task | asyncio wrapper to schedule and execute coroutines on the event loop. |
repeat_task() | Function scheduling a task at regular intervals using an event loop. |
Additional Details
Handling Exceptions
When dealing with I/O operations or long-running processes, it’s essential to handle exceptions to ensure the program's robustness. You can modify the repeat_task function to catch and handle any potential errors gracefully:
Use Cases
- Monitoring Systems: Periodically check system health or metrics.
- Data Fetching: Regularly pull data from external APIs.
- Automated Processes: Execute routine operations in background applications.
Performance Considerations
Asynchronous programming can significantly enhance performance for I/O-bound tasks. However, it's essential to recognize that asyncio is best suited for tasks that involve waiting (e.g., network, file I/O) and may not provide significant benefits for CPU-bound operations.
Conclusion
Executing functions asynchronously at regular intervals is a powerful capability in Python, especially for applications requiring periodic tasks. By leveraging asyncio, developers can build efficient, non-blocking systems. Understanding these fundamentals and embracing the concepts of coroutines, event loops, and tasks is crucial for enhancing your applications with asynchronous capabilities.
Related reading
- How to exit all running threads?
- How to exit all running threads?
- How to exit the entire application from a Python thread?
- How to find an optimum number of processes in GridSearchCV ..., n_jobs ... ?
- How to execute a Python script from the Django shell?
- How to execute multi-line statements within Python's own debugger PDB
- How to find what state ManualResetEvent is in?
- How to find what state ManualResetEvent is in?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.