Procrastinate

3.8.1 · active · verified Wed Apr 15

Procrastinate is an open-source Python 3.10+ distributed task processing library that leverages PostgreSQL 13+ to store task definitions, manage locks, and dispatch tasks. It integrates with both synchronous and asynchronous code, offers Django integration, and is compatible with ASGI frameworks, supporting features like periodic tasks, retries, and arbitrary task locks.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a Procrastinate application, declare a task, and defer a job. It assumes a PostgreSQL database is running and accessible via `POSTGRES_DSN`. To run the worker that executes deferred tasks, a separate CLI command is provided.

import random
import time
import os

from procrastinate import App, PsycopgConnector

# Configure your PostgreSQL connection string
# Example: 'postgresql://user:password@host:port/database'
# Use os.environ.get for production readiness
POSTGRES_DSN = os.environ.get('POSTGRES_DSN', 'postgresql://postgres:password@localhost:5432/postgres')

app = App(
    connector=PsycopgConnector(
        dsn=POSTGRES_DSN
    )
)

@app.task(name="sum_task")
def sum_task(a, b):
    time.sleep(random.random() * 0.5) # Simulate work
    result = a + b
    print(f"Task sum_task({a}, {b}) finished with result: {result}")
    return result

async def main():
    print("Applying schema...")
    await app.open_async()
    await app.get_connector().check()
    await app.get_connector().execute_query_one("SELECT 1 FROM procrastinate_jobs LIMIT 1")
    print("Schema applied and checked.")

    print("Deferring a job...")
    job = await sum_task.defer_async(a=3, b=5)
    print(f"Job deferred with ID: {job.id}")
    await app.close_async()

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

# To run the worker, save the above as e.g., 'my_tasks.py' and execute in a separate terminal:
# export POSTGRES_DSN='postgresql://postgres:password@localhost:5432/postgres' # (or your actual DSN)
# procrastinate --app=my_tasks.app worker

view raw JSON →