async-tasks-python


Nameasync-tasks-python JSON
Version 1.0.0 PyPI version JSON
download
home_pagehttps://del.wang
SummaryAsync tasks made simple—multi-threaded, stoppable, and timeout-ready.
upload_time2024-11-07 01:12:39
maintainerDel Wang
docs_urlNone
authorDel Wang
requires_python<4.0,>=3.8
licenseMIT
keywords async tasks threading stoppable
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # async-tasks

<a href="https://pypi.python.org/pypi/async-tasks-python"><img src="http://img.shields.io/pypi/v/async-tasks-python.svg" alt="Latest version on PyPI"></a> <a href="https://pypi.python.org/pypi/async-tasks-python"><img src="https://img.shields.io/pypi/pyversions/async-tasks-python.svg" alt="Compatible Python versions."></a>

A Python library for managing asynchronous tasks—supporting multi-threading, task cancellation, and timeout handling.

## Key Features

- **Timeout Handling**: Automatically stops tasks that exceed a specified time limit.
- **Task Cancellation**: Provides the ability to stop or cancel tasks at any point during execution.
- **Multi-threading**: Runs tasks asynchronously in separate threads to avoid blocking the main thread.

## Installation

To install `async-tasks`, simply run:

```bash
pip install async-tasks-python
```

## Usage Example

### Basic Example: Running and Stopping a Task

```python
import time
from async_tasks import AsyncTask

# Define a long-running task
def long_running_task():
    for i in range(10):
        time.sleep(1)  # Simulate work with a 1-second delay
        print(f"Task running... {i + 1}")
    return "Task completed successfully"

# Run the task asynchronously in a separate thread
task = AsyncTask.run_async(long_running_task, task_id="task1")

# Stop the task after 3 seconds
time.sleep(3)
task.stop()

# Alternatively, cancel the task using its task ID
AsyncTask.cancel("task1")
```

### Example: Timeout and Callback

```python
import time
from async_tasks import AsyncTask

# Define a long-running task
def long_running_task():
    for i in range(10):
        time.sleep(1)  # Simulate work with a 1-second delay
        print(f"Task running... {i + 1}")
    return "Task completed successfully"

# Define a callback function to handle task completion
def on_completion(result, error):
    print("\n✅ Task finished")
    if error:
        print(f"Error: {error}")
    else:
        print(f"Result: {result}")

# Run the task with a timeout (3 seconds)
# If the task exceeds this time, it will be automatically stopped
AsyncTask.run_async(
    long_running_task,
    timeout=3,  # Task will stop if it takes longer than 3 seconds
    on_completion=on_completion,  # Callback function on task completion
)

# Allow some time for the task to run and timeout
time.sleep(5)
```

### Example: Managing a Thread Pool with `AsyncTasksExecutor`

You can manage a pool of asynchronous tasks in a manner similar to using `ThreadPoolExecutor`. This allows you to control the number of concurrent tasks and efficiently manage resources. In this example, we will submit multiple tasks to the executor, track their progress, and handle task completion.

```python
from queue import Queue
from time import sleep

import tqdm

from async_tasks.executor import AsyncTasksExecutor

# Number of concurrent workers
max_workers = 5

# Initialize result storage and result queue
results = []
result_queue = Queue()


def process_task(idx: int) -> None:
    try:
        sleep(1)  # Simulate work with a 1-second delay
        if idx % 2:  # Simulate failure for tasks with odd indices
            raise Exception(f"Task {idx + 1} failed")

        # If the task succeeds, put the result in the queue
        result_queue.put((None, f"Task {idx + 1} completed successfully"))
    except Exception as err:
        result_queue.put((err, None))  # In case of failure, put the error in the queue


# Create an AsyncTasksExecutor to manage a pool of concurrent threads
with AsyncTasksExecutor(max_workers=max_workers) as executor:
    # Submit tasks to the executor
    for idx in range(10):
        executor.submit(process_task, idx)

    # Track and display progress using tqdm for a progress bar
    completed = 0
    with tqdm.tqdm(total=10, desc="Processing Tasks") as process_bar:
        try:
            while completed < 10:
                # Retrieve the result of a completed task from the queue
                res = result_queue.get()
                results.append(res)
                completed += 1
                process_bar.update(1)  # Update the progress bar
        except KeyboardInterrupt:
            # Gracefully handle KeyboardInterrupt and shut down the executor
            print("\nProcess interrupted. Shutting down executor...")
            executor.shutdown()

# Optionally, print the results
print("\nAll tasks completed:")
for result in results:
    print(result)
```

## License

This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.

            

Raw data

            {
    "_id": null,
    "home_page": "https://del.wang",
    "name": "async-tasks-python",
    "maintainer": "Del Wang",
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": "hello@xbox.work",
    "keywords": "async, tasks, threading, stoppable",
    "author": "Del Wang",
    "author_email": "hello@xbox.work",
    "download_url": "https://files.pythonhosted.org/packages/e6/27/fe107097e484da81e90d0796a4ec3805a1506f5d1d4f2bd43f0679b0bc72/async_tasks_python-1.0.0.tar.gz",
    "platform": null,
    "description": "# async-tasks\n\n<a href=\"https://pypi.python.org/pypi/async-tasks-python\"><img src=\"http://img.shields.io/pypi/v/async-tasks-python.svg\" alt=\"Latest version on PyPI\"></a> <a href=\"https://pypi.python.org/pypi/async-tasks-python\"><img src=\"https://img.shields.io/pypi/pyversions/async-tasks-python.svg\" alt=\"Compatible Python versions.\"></a>\n\nA Python library for managing asynchronous tasks\u2014supporting multi-threading, task cancellation, and timeout handling.\n\n## Key Features\n\n- **Timeout Handling**: Automatically stops tasks that exceed a specified time limit.\n- **Task Cancellation**: Provides the ability to stop or cancel tasks at any point during execution.\n- **Multi-threading**: Runs tasks asynchronously in separate threads to avoid blocking the main thread.\n\n## Installation\n\nTo install `async-tasks`, simply run:\n\n```bash\npip install async-tasks-python\n```\n\n## Usage Example\n\n### Basic Example: Running and Stopping a Task\n\n```python\nimport time\nfrom async_tasks import AsyncTask\n\n# Define a long-running task\ndef long_running_task():\n    for i in range(10):\n        time.sleep(1)  # Simulate work with a 1-second delay\n        print(f\"Task running... {i + 1}\")\n    return \"Task completed successfully\"\n\n# Run the task asynchronously in a separate thread\ntask = AsyncTask.run_async(long_running_task, task_id=\"task1\")\n\n# Stop the task after 3 seconds\ntime.sleep(3)\ntask.stop()\n\n# Alternatively, cancel the task using its task ID\nAsyncTask.cancel(\"task1\")\n```\n\n### Example: Timeout and Callback\n\n```python\nimport time\nfrom async_tasks import AsyncTask\n\n# Define a long-running task\ndef long_running_task():\n    for i in range(10):\n        time.sleep(1)  # Simulate work with a 1-second delay\n        print(f\"Task running... {i + 1}\")\n    return \"Task completed successfully\"\n\n# Define a callback function to handle task completion\ndef on_completion(result, error):\n    print(\"\\n\u2705 Task finished\")\n    if error:\n        print(f\"Error: {error}\")\n    else:\n        print(f\"Result: {result}\")\n\n# Run the task with a timeout (3 seconds)\n# If the task exceeds this time, it will be automatically stopped\nAsyncTask.run_async(\n    long_running_task,\n    timeout=3,  # Task will stop if it takes longer than 3 seconds\n    on_completion=on_completion,  # Callback function on task completion\n)\n\n# Allow some time for the task to run and timeout\ntime.sleep(5)\n```\n\n### Example: Managing a Thread Pool with `AsyncTasksExecutor`\n\nYou can manage a pool of asynchronous tasks in a manner similar to using `ThreadPoolExecutor`. This allows you to control the number of concurrent tasks and efficiently manage resources. In this example, we will submit multiple tasks to the executor, track their progress, and handle task completion.\n\n```python\nfrom queue import Queue\nfrom time import sleep\n\nimport tqdm\n\nfrom async_tasks.executor import AsyncTasksExecutor\n\n# Number of concurrent workers\nmax_workers = 5\n\n# Initialize result storage and result queue\nresults = []\nresult_queue = Queue()\n\n\ndef process_task(idx: int) -> None:\n    try:\n        sleep(1)  # Simulate work with a 1-second delay\n        if idx % 2:  # Simulate failure for tasks with odd indices\n            raise Exception(f\"Task {idx + 1} failed\")\n\n        # If the task succeeds, put the result in the queue\n        result_queue.put((None, f\"Task {idx + 1} completed successfully\"))\n    except Exception as err:\n        result_queue.put((err, None))  # In case of failure, put the error in the queue\n\n\n# Create an AsyncTasksExecutor to manage a pool of concurrent threads\nwith AsyncTasksExecutor(max_workers=max_workers) as executor:\n    # Submit tasks to the executor\n    for idx in range(10):\n        executor.submit(process_task, idx)\n\n    # Track and display progress using tqdm for a progress bar\n    completed = 0\n    with tqdm.tqdm(total=10, desc=\"Processing Tasks\") as process_bar:\n        try:\n            while completed < 10:\n                # Retrieve the result of a completed task from the queue\n                res = result_queue.get()\n                results.append(res)\n                completed += 1\n                process_bar.update(1)  # Update the progress bar\n        except KeyboardInterrupt:\n            # Gracefully handle KeyboardInterrupt and shut down the executor\n            print(\"\\nProcess interrupted. Shutting down executor...\")\n            executor.shutdown()\n\n# Optionally, print the results\nprint(\"\\nAll tasks completed:\")\nfor result in results:\n    print(result)\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Async tasks made simple\u2014multi-threaded, stoppable, and timeout-ready.",
    "version": "1.0.0",
    "project_urls": {
        "Changelog": "https://github.com/idootop/async-tasks/blob/main/CHANGELOG.md",
        "Documentation": "https://github.com/idootop/async-tasks/README.md",
        "Homepage": "https://del.wang",
        "Repository": "https://github.com/idootop/async-tasks"
    },
    "split_keywords": [
        "async",
        " tasks",
        " threading",
        " stoppable"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4275f2ea964f3f25f48834b28f323244800eac23f069f41b0c93560d943ef8cf",
                "md5": "751b6d0b92e5f4b9c9b7dd207289042a",
                "sha256": "e52dddee63911caf58aae524367401637f8431d544a83af679e0e829ed84019e"
            },
            "downloads": -1,
            "filename": "async_tasks_python-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "751b6d0b92e5f4b9c9b7dd207289042a",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 6144,
            "upload_time": "2024-11-07T01:12:37",
            "upload_time_iso_8601": "2024-11-07T01:12:37.662426Z",
            "url": "https://files.pythonhosted.org/packages/42/75/f2ea964f3f25f48834b28f323244800eac23f069f41b0c93560d943ef8cf/async_tasks_python-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e627fe107097e484da81e90d0796a4ec3805a1506f5d1d4f2bd43f0679b0bc72",
                "md5": "37d41ea628dbc2c59e10baf8831fc3e5",
                "sha256": "85713376a07df102c4cd1b1d8c93b04ad0b0cd685051d3a66bc35edab106427d"
            },
            "downloads": -1,
            "filename": "async_tasks_python-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "37d41ea628dbc2c59e10baf8831fc3e5",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 4991,
            "upload_time": "2024-11-07T01:12:39",
            "upload_time_iso_8601": "2024-11-07T01:12:39.649268Z",
            "url": "https://files.pythonhosted.org/packages/e6/27/fe107097e484da81e90d0796a4ec3805a1506f5d1d4f2bd43f0679b0bc72/async_tasks_python-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-07 01:12:39",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "idootop",
    "github_project": "async-tasks",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "async-tasks-python"
}
        
Elapsed time: 0.36243s