asynchronous programming
Python
scheduling tasks
Python tips
cron jobs

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.

Browse interview questions

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 contains await expressions 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.

python
import asyncio
import time

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.

python
1async def my_task():
2    print(f"Task started at {time.strftime('%X')}")
3    # Simulate a delay (e.g., network request)
4    await asyncio.sleep(2)
5    print(f"Task completed at {time.strftime('%X')}")

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.

python
1async def repeat_task(interval):
2    while True:
3        await my_task()
4        await asyncio.sleep(interval)

Step 4: Run the Event Loop

Finally, initialize the event loop and schedule the repeating task.

python
1def main():
2    loop = asyncio.get_event_loop()
3    try:
4        loop.run_until_complete(repeat_task(60))
5    except KeyboardInterrupt:
6        pass
7    finally:
8        loop.close()
9
10if __name__ == '__main__':
11    main()

Explanation

  1. async def my_task(): Defines an asynchronous function that performs the task. It uses await asyncio.sleep(2) to simulate work.
  2. repeat_task(interval): Continuously runs my_task() followed by a sleep period equal to the specified interval (60 seconds).
  3. loop.run_until_complete(): Starts the event loop to run repeat_task() until it’s terminated (e.g., with a keyboard interrupt).

Table Summary

ConceptDescription
AsynchronousNon-blocking, concurrent code execution using coroutines.
Event LoopCentral component running tasks and managing coroutines.
CoroutineFunction that can be paused and resumed using await.
Taskasyncio 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:

python
1async def repeat_task(interval):
2    while True:
3        try:
4            await my_task()
5        except Exception as e:
6            print(f"An error occurred: {e}")
7        await asyncio.sleep(interval)

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
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.