Skip to main content

Django library for managing asynchronous tasks with scheduling and dependency management

Project description

Django Async Manager

Django library for managing asynchronous tasks with scheduling and dependency management.

Features

  • Background Tasks: Run Django functions asynchronously in the background
  • Task Scheduling: Schedule tasks to run at specific times using cron-like syntax
  • Task Dependencies: Define dependencies between tasks to ensure proper execution order
  • Priority Queues: Assign priorities to tasks and process them accordingly
  • Automatic Retries: Configure automatic retries with exponential backoff for failed tasks
  • Multiple Workers: Run multiple workers using threads or processes
  • Task Timeouts: Set timeouts for long-running tasks
  • Monitoring: Track task status, execution time, and errors

Installation

From PyPI (recommended)

pip install django-async-manager

From Local Directory

To install the package from a local directory (for development or testing):

# Navigate to the directory containing the package
cd /path/to/django-async-manager

# Install in development mode
pip install -e .

Quick Start

  1. Add 'django_async_manager' to your INSTALLED_APPS in settings.py:
INSTALLED_APPS = [
    # ...
    'django_async_manager',
    # ...
]
  1. Run migrations to create the necessary database tables:
python manage.py migrate django_async_manager
  1. Define a background task:
from django_async_manager.decorators import background_task

@background_task(priority="high", max_retries=3)
def process_data(user_id, data):
    # Your long-running code here
    return result
  1. Call the task asynchronously:
# This will create a task and return immediately
task = process_data.run_async(user_id=123, data={"key": "value"})

# You can check the task status later
print(f"Task status: {task.status}")
  1. Start a worker to process tasks:
python manage.py run_worker --num-workers=2

Scheduling Periodic Tasks

  1. Define your schedule in settings.py:
BEAT_SCHEDULE = {
    'daily-report': {
        'task': 'myapp.tasks.generate_daily_report',
        'schedule': {
            'hour': '0',  # Run at midnight
            'minute': '0',
        },
        'args': [],
        'kwargs': {'send_email': True},
    },
}
  1. Update the schedule in the database:
python manage.py update_beat_schedule
  1. Start the scheduler:
python manage.py run_scheduler

Advanced Usage

Task Dependencies

# Create a dependent task that will only run after task1 and task2 are completed
dependent_task = generate_report.run_async(dependencies=[task1, task2])

Task Queues

@background_task(queue="email")
def send_email(to, subject, body):
    # Send email logic
    pass

# Start a worker for the email queue
# python manage.py run_worker --queue=email

Worker Execution Modes

By default, workers run in thread mode, but you can also run them as separate processes:

# Run workers in thread mode (default)
python manage.py run_worker --num-workers=2 --queue=default

# Run workers in process mode
python manage.py run_worker --num-workers=2 --processes --queue=default

Thread mode is more memory-efficient but may be affected by Python's Global Interpreter Lock (GIL). Process mode provides true parallelism but uses more memory.

Timeout Configuration

@background_task(timeout=60)  # 60 seconds timeout
def process_large_file(file_path):
    # Process file
    pass

Task Priority

You can assign different priority levels to tasks:

@background_task(priority="high")  # Options: "low", "medium", "high", "critical"
def important_task():
    # High priority operation
    pass

Tasks are processed in order of priority, with higher priority tasks being executed first.

Retry Configuration

You can configure automatic retries for failed tasks:

@background_task(
    max_retries=3,           # Maximum number of retry attempts
    retry_delay=60,          # Initial delay between retries in seconds
    retry_backoff=2.0        # Multiplier for increasing delay between retries
)
def unreliable_operation():
    # Operation that might fail
    pass

With the above configuration, retries would occur after 60s, 120s, and 240s (with exponential backoff).

Decorator Parameters Reference

The @background_task decorator accepts the following parameters:

@background_task(
    priority="medium",       # Task priority: "low", "medium", "high", "critical"
    queue="default",         # Queue name for task processing
    dependencies=None,       # Tasks that must complete before this task runs
    autoretry=True,          # Whether to automatically retry failed tasks
    retry_delay=60,          # Initial delay between retries in seconds
    retry_backoff=2.0,       # Multiplier for increasing delay between retries
    max_retries=1,           # Maximum number of retry attempts
    timeout=300,             # Maximum execution time in seconds
)
def my_task():
    # Task implementation
    pass

Logging Configuration

Django Async Manager uses Python's standard logging module to log information about task execution, scheduling, and errors. By default, the package configures basic logging for its management commands to ensure logs are visible even without explicit configuration.

Default Loggers

The package uses the following loggers:

  • django_async_manager.worker: For worker-related logs (task execution, errors)
  • django_async_manager.scheduler: For scheduler-related logs (periodic tasks, scheduling)

Customizing Logging

To customize logging in your project, add the following configuration to your Django settings:

LOGGING = {
    # Your existing logging configuration...

    "formatters": {
        "verbose": {
            "format": "{asctime} - {levelname} - {name} - {message}",
            "style": "{",
        },
        # Other formatters...
    },
    "handlers": {
        "console": {
            "level": "DEBUG",
            "class": "logging.StreamHandler",
            "formatter": "verbose",
        },
        "file": {
            "level": "INFO",
            "class": "logging.FileHandler",
            "filename": "django_async_manager.log",  # Customize the path as needed
            "formatter": "verbose",
        },
        # Other handlers...
    },
    "loggers": {
        "django_async_manager.worker": {
            "handlers": ["console", "file"],
            "level": "DEBUG",
            "propagate": False,
        },
        "django_async_manager.scheduler": {
            "handlers": ["console", "file"],
            "level": "DEBUG",
            "propagate": False,
        },
        # Other loggers...
    },
}

This configuration will ensure that logs from Django Async Manager are properly captured and displayed in your project.

License

MIT License

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_async_manager-0.1.1.tar.gz (26.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_async_manager-0.1.1-py3-none-any.whl (34.0 kB view details)

Uploaded Python 3

File details

Details for the file django_async_manager-0.1.1.tar.gz.

File metadata

  • Download URL: django_async_manager-0.1.1.tar.gz
  • Upload date:
  • Size: 26.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for django_async_manager-0.1.1.tar.gz
Algorithm Hash digest
SHA256 77e8b6d16215a79302967bed0efdbac2918647c906f4cdb2f28138e220f83b80
MD5 d0001e8118fd32f29a55d3c41657f9b2
BLAKE2b-256 eeefd3d07305f7e0290484b22becc5d3f56d2ce87fc855d236e974f8cdaada7f

See more details on using hashes here.

File details

Details for the file django_async_manager-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for django_async_manager-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e5836bd8a98aacac924e136a52a6eda325984817f9078f15fc341f7ab3892198
MD5 fc2a1c7ab4e19e6fd34ddebb6e5b6add
BLAKE2b-256 53f498427f0c75332cdc1c9e3e117f9b0744cb9f23ba7d89beee7ba48768c825

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page