Skip to main content

TaskEx

A minimal-dependency, pure Python library for running async functions, sync functions, and shell commands as tracked asynchronous tasks.

PyPI version License PyPI - Python Version

Package TaskEx
Version 0.3.0
Python >= 3.11
Dependencies pydantic
Download https://pypi.org/project/taskex/
Source https://github.com/adalundhe/taskex
Keywords async, tasks, runner, shell, jobs, executor

Features

  • Unified async interface — Run async def coroutines, blocking Python functions (via ProcessPoolExecutor, ThreadPoolExecutor, or the default asyncio thread pool), and subprocess/shell commands through one TaskRunner API.
  • Token-based tracking — Every execution receives a unique Snowflake-based run.token ("<task_name>:<run_id>") for status queries, live output inspection, awaiting, or cancellation.
  • Structured Pydantic results — Inspect runs with typed TaskRun and ShellProcess models (including status, return code, stdout/stderr, error message, traceback, and monotonic timing).
  • Non-blocking shell I/O & clean reaping — Subprocess stdout and stderr are drained concurrently to prevent pipe deadlocks and preserve complete output across polling calls. Timeouts and cancellations terminate and reap process groups cleanly.
  • Scheduling & retention policies — Run recurring jobs on human-readable intervals ("500ms", "30s", "1h 30m") with fixed or infinite repeats, and bound in-memory run history using COUNT, AGE, or COUNT_AND_AGE cleanup policies.
  • Graceful lifecycle management — Use async with TaskRunner() as runner:, stop() (cancel runs while keeping the runner active), shutdown() (graceful teardown), or abort() (immediate synchronous teardown).

Installation

pip install taskex

Or with uv:

uv add taskex

Quick Start

Running an async function

import asyncio
from taskex import Env, TaskRunner


async def fetch_value(x: int) -> int:
    await asyncio.sleep(0.1)
    return x * 2


async def main() -> None:
    async with TaskRunner(config=Env(MERCURY_SYNC_EXECUTOR_TYPE="none")) as runner:
        run = runner.run(fetch_value, 21)
        result = await runner.wait(run.token)
        print(result.status, result.result)  # RunStatus.COMPLETE 42


asyncio.run(main())

Running a blocking sync function

Synchronous callables are automatically offloaded to the configured executor ("process" by default, "thread", or "none" for asyncio's default thread pool) and concurrency-limited by MERCURY_SYNC_TASK_RUNNER_MAX_THREADS:

import asyncio
from taskex import Env, TaskRunner


def compute_sum(n: int) -> int:
    return sum(range(n))


async def main() -> None:
    config = Env(
        MERCURY_SYNC_EXECUTOR_TYPE="thread",
        MERCURY_SYNC_TASK_RUNNER_MAX_THREADS=4,
    )
    async with TaskRunner(config=config) as runner:
        runs = [runner.run(compute_sum, 100_000) for _ in range(4)]
        results = await runner.wait_all([r.token for r in runs])
        print([r.result for r in results])


asyncio.run(main())

Running a shell command

import asyncio
from taskex import Env, ShellProcess, TaskRunner


async def main() -> None:
    async with TaskRunner(config=Env(MERCURY_SYNC_EXECUTOR_TYPE="none")) as runner:
        run = runner.command(
            "ls",
            "-la",
            alias="list_files",
            timeout="10s",
        )
        output: ShellProcess = await runner.wait(run.token)
        print("Exit code:", output.return_code)
        print(output.result)


asyncio.run(main())

Scheduling recurring tasks

import asyncio
from taskex import Env, TaskRunner


async def heartbeat() -> str:
    return "alive"


async def main() -> None:
    async with TaskRunner(config=Env(MERCURY_SYNC_EXECUTOR_TYPE="none")) as runner:
        run = runner.run(
            heartbeat,
            alias="heartbeat",
            schedule="500ms",
            repeat=3,
            keep=5,
            keep_policy="COUNT",
        )
        await runner.wait(run.token)
        await asyncio.sleep(1.5)


asyncio.run(main())

Configuration Overview

Pass an Env model to TaskRunner(instance_id=0, config=Env(...)):

Setting Type Default Description
MERCURY_SYNC_EXECUTOR_TYPE "process" | "thread" | "none" "process" Executor used for synchronous callables ("none" uses asyncio's default thread pool).
MERCURY_SYNC_TASK_RUNNER_MAX_THREADS int (>= 1) os.cpu_count() or 1 Maximum concurrent workers and semaphore permits for sync callables.
MERCURY_SYNC_CLEANUP_INTERVAL str (duration) "1s" Interval between background cleanup passes (COUNT / AGE eviction).
MERCURY_SYNC_LOG_LEVEL str "info" Log level configuration value.

See docs/configuration.md for the full configuration reference.


Documentation

Examples

Runnable scripts are available in examples/:


Development & Testing

uv venv
uv pip install pydantic pytest pytest-asyncio
.venv/bin/python -m pytest -v tests/

License

MIT — see LICENSE.

Metadata

Release files for taskex 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for taskex 0.3.0
File Size Uploaded Provenance Actions
taskex-0.3.0.tar.gz 28.0 kB Without provenance Details for taskex-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for taskex 0.3.0
File Interpreter ABI Platform Actions
taskex-0.3.0-py3-none-any.whl Python 3 none any Details for taskex-0.3.0-py3-none-any.whl

Total release size: 50.1 kB

Release files / taskex-0.3.0.tar.gz

Download URL taskex-0.3.0.tar.gz
Size 28.0 kB
Tags Source
SHA-256 checksum
How to use checksums
4868e1e4e2a7b50e10a474520fc9f2e3436ddb50b9016898d8d040ab57d3ae75
BLAKE2b-256 checksum
How to use checksums
553d2caf4d3050177ba06dee1af87acb9dca2235fd7ee27ddaf43af381879860
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / taskex-0.3.0-py3-none-any.whl

Download URL taskex-0.3.0-py3-none-any.whl
Size 22.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
faed0f27e92cb0f06046e03adb50061958bd9d0d82d04fff26494c2aad0cdbd5
BLAKE2b-256 checksum
How to use checksums
ffff35214d0f33a7d0bda26eea166bbd284ce6b08c6a03a307b2059e4dc7dc0b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for taskex 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.3.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page