Certainly! Below is the complete implementation of the ThreadWorker class that supports scheduling both synchronous and asynchronous functions with optional callbacks, delays, and arguments. Additionally, an example usage is provided to demonstrate how to utilize the ThreadWorker effectively.
ThreadWorker Class Implementation
import asyncio
import threading
from typing import Callable, Optional, Any
class ThreadWorker:
def __init__(self):
"""
Initializes the ThreadWorker by starting a new thread
that runs an asyncio event loop.
"""
self.loop = None
self.thread = threading.Thread(target=self.loop_task, daemon=True)
self.thread.start()
def loop_task(self):
"""Starts the asyncio event loop in a separate thread."""
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop)
self.loop.run_forever()
def join(self, timeout: Optional[float] = None):
"""
Waits for the worker thread to finish.
:param timeout: Optional timeout in seconds.
"""
self.thread.join(timeout)
def after(
self,
func: Callable[..., Any],
callback: Optional[Callable[[Any], None]] = None,
delay: Optional[float] = None,
args: Optional[Any] = None
):
"""
Schedules a function or coroutine to be executed in the event loop.
:param func: The function or coroutine to execute.
:param callback: Optional function to call with the result.
:param delay: Optional delay in seconds before execution.
:param args: Optional positional arguments to pass to `func`.
"""
if args is None:
args = ()
async def task():
if delay:
await asyncio.sleep(delay)
if asyncio.iscoroutinefunction(func):
result = await func(*args)
else:
result = func(*args)
if callback:
if asyncio.iscoroutinefunction(callback):
await callback(result)
else:
# If callback is a regular function, run it in the default executor
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, callback, result)
# Schedule the coroutine to run in the event loop thread
asyncio.run_coroutine_threadsafe(task(), self.loop)
async def after_async(
self,
func: Callable[..., Any],
delay: Optional[float] = None,
args: Optional[Any] = None
) -> Any:
"""
Asynchronously schedules a function or coroutine to be executed in the event loop
and awaits its result.
:param func: The function or coroutine to execute.
:param delay: Optional delay in seconds before execution.
:param args: Optional positional arguments to pass to `func`.
:return: The result of `func`.
"""
if args is None:
args = ()
if delay:
await asyncio.sleep(delay)
if asyncio.iscoroutinefunction(func):
return await func(*args)
else:
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, func, *args)
def stop(self):
"""
Stops the event loop and joins the thread.
"""
if self.loop and self.loop.is_running():
self.loop.call_soon_threadsafe(self.loop.stop)
self.join()
def __del__(self):
"""
Ensures the event loop is stopped when the ThreadWorker is garbage collected.
"""
self.stop()
Explanation of Key Components
-
Initialization (__init__ and loop_task):
- A new thread is started upon initialization, which runs the
loop_task method.
loop_task initializes a new asyncio event loop and starts it with run_forever(), keeping it alive to process scheduled tasks.
-
after Method:
- Allows scheduling both synchronous and asynchronous functions to be executed in the worker's event loop.
- Supports optional delays (
delay), arguments (args), and callbacks (callback).
- If a
delay is specified, the task waits for the given duration before execution.
- If a
callback is provided, it is called with the result of func after func completes. Callbacks can be either synchronous or asynchronous.
-
after_async Method:
- An asynchronous method that schedules a function or coroutine to run in the event loop and awaits its completion.
- Useful for chaining tasks within coroutines running in the worker's event loop.
- Handles both synchronous and asynchronous
func similarly to the after method.
-
Stopping and Cleanup (stop and __del__):
- The
stop method gracefully stops the event loop and joins the thread.
- The
__del__ method ensures that resources are cleaned up when the ThreadWorker instance is garbage collected.
Example Usage
Below is an example demonstrating how to use the ThreadWorker class to schedule tasks with various configurations, including delays and callbacks.
import asyncio
from typing import Any
# Assuming ThreadWorker is already defined as above
def task1(a, b, c):
print(f"[task1] Executed with arguments: {a}, {b}, {c}")
return f"Result from task1 with args ({a}, {b}, {c})"
async def task2():
print("[task2] Started")
await asyncio.sleep(1)
print("[task2] Completed")
return "Result from task2"
async def task3(worker: ThreadWorker):
print("[task3] Awaiting task1 with 2-second delay")
result = await worker.after_async(task1, delay=2, args=(1, 2, 3))
print(f"[task3] Received: {result}")
await asyncio.sleep(1)
print("[task3] Printing 'Foo'")
print("Foo")
print("[task3] Stopping worker")
worker.stop()
def callback(result: Any):
print(f"[callback] Received: {result}")
# Initialize the worker
worker = ThreadWorker()
# Schedule various tasks
worker.after(task1, args=(10, 20, 30)) # Synchronous task without callback
worker.after(task2, callback=callback) # Asynchronous task with callback
worker.after(task1, callback=callback, delay=3, args=(40, 50, 60)) # Synchronous task with callback and delay
worker.after(task1, args=(70, 80, 90)) # Another synchronous task without callback
# Schedule an asynchronous task that utilizes after_async
worker.after(task3, args=(worker,))
# Wait for the worker thread to finish
worker.join()
print("Worker has been stopped.")
Expected Output
[task1] Executed with arguments: 10, 20, 30
[task2] Started
[task2] Completed
[callback] Received: Result from task2
[task1] Executed with arguments: 40, 50, 60
[callback] Received: Result from task1 with args (40, 50, 60)
[task1] Executed with arguments: 70, 80, 90
[task3] Awaiting task1 with 2-second delay
[task1] Executed with arguments: 1, 2, 3
[task3] Received: Result from task1 with args (1, 2, 3)
[task3] Printing 'Foo'
Foo
[task3] Stopping worker
Worker has been stopped.
Breakdown of the Example
-
Scheduling task1 Without Callback:
- Immediately executes
task1 with arguments (10, 20, 30).
- Since no delay is specified, it runs as soon as possible.
-
Scheduling task2 With Callback:
- Executes the asynchronous
task2.
- Once
task2 completes, the callback function is invoked with the result.
-
Scheduling task1 With Callback and Delay:
- Schedules
task1 to run after a 3-second delay with arguments (40, 50, 60).
- Upon completion, the
callback is invoked with the result.
-
Scheduling Another task1 Without Callback:
- Executes another instance of
task1 with different arguments.
-
Scheduling task3:
task3 is an asynchronous coroutine that:
- Waits for
task1 to execute with a 2-second delay and awaits its result using after_async.
- Sleeps for an additional second.
- Prints "Foo".
- Stops the
ThreadWorker.
-
Joining the Worker:
- The main thread waits for the worker thread to finish execution by calling
worker.join().
- Once all tasks are completed and the worker is stopped, it prints "Worker has been stopped."
Notes and Best Practices
-
Thread Safety: The after method uses asyncio.run_coroutine_threadsafe to safely schedule tasks from the main thread to the worker's event loop running in a separate thread.
-
Callbacks: Callbacks can be either synchronous or asynchronous. Synchronous callbacks are executed in the default executor to prevent blocking the event loop.
-
Graceful Shutdown: Always ensure that the worker is properly stopped to clean up resources. This example demonstrates stopping the worker from within a scheduled coroutine (task3).
-
Exception Handling: For production code, consider adding exception handling within the task coroutine in the after method to manage potential errors gracefully.
By following this implementation and example, you can effectively manage background tasks using asyncio within a separate thread, providing flexibility and concurrency in your applications.