मुख्य सामग्री पर जाएँ
Skillpedia
API और सर्वर (backend)41k · #6757

python-background-jobs

यह क्या करती है

यह skill लंबे समय तक चलने वाले कामों को व्यवस्थित करने में मदद करती है, जैसे बड़ी संख्या में emails भेजना या report बनाना। इससे आपका program उपयोगकर्ता को तुरंत जवाब दे सकता है, जबकि भारी काम background में होता रहता है।

कब इस्तेमाल करें

  • ✓एक साथ बहुत सारे emails भेजना।
  • ✓कोई बड़ी report बनाना जिसमें समय लगे।
  • ✓कोई file upload प्रोसेस करना जिसमें समय लगे।

Skill का लिंक

https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-background-jobs/SKILL.md

इसे कॉपी करके अपने AI (Claude, ChatGPT या Cursor) में पेस्ट करें और निर्देशों का पालन करने को कहें।

कैसे इस्तेमाल करें

सबसे आसान तरीका: मैसेज कॉपी करके अपने AI में पेस्ट करें। वह skill पढ़कर निर्देशों का पालन करेगा।

पेस्ट करने के लिए तैयार मैसेज

इस skill से मेरी मदद करो: https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-background-jobs/SKILL.md इस लिंक की SKILL.md फ़ाइल पढ़ो और मेरे काम में उसके निर्देशों का पालन करो।
क्या आप चाहते हैं कि आपका AI ऐसी skills खुद ढूँढे?मुफ़्त Skillpedia MCP इंस्टॉल करें: बस एक लाइन, और हर काम से पहले यह 15,000+ skills में खोजता है।1 मिनट में इंस्टॉल करें →

AI से क्या माँगें: उदाहरण

“मैं अपने program से 1000 लोगों को email भेजूं, और program अटके नहीं, ऐसा कैसे करूं?”

हर हफ़्ते 5 नई skills, 1 मिनट में पढ़ें।

यह कैसे काम करती है

आपका program एक 'task' को queue में भेज देता है। एक अलग 'worker' इस task को उठाकर चलाता है। इससे आपका मुख्य program बाकी काम करने के लिए खाली रहता है।

तकनीकी सामग्री (मूल SKILL.md)

लेखक का मूल टेक्स्ट, अंग्रेज़ी में, सीधे GitHub से।

Python Background Jobs & Task Queues

Decouple long-running or unreliable work from request/response cycles. Return immediately to the user while background workers handle the heavy lifting asynchronously.

When to Use This Skill

  • Processing tasks that take longer than a few seconds
  • Sending emails, notifications, or webhooks
  • Generating reports or exporting data
  • Processing uploads or media transformations
  • Integrating with unreliable external services
  • Building event-driven architectures

Core Concepts

1. Task Queue Pattern

API accepts request, enqueues a job, returns immediately with a job ID. Workers process jobs asynchronously.

2. Idempotency

Tasks may be retried on failure. Design for safe re-execution.

3. Job State Machine

Jobs transition through states: pending → running → succeeded/failed.

4. At-Least-Once Delivery

Most queues guarantee at-least-once delivery. Your code must handle duplicates.

Quick Start

This skill uses Celery for examples, a widely adopted task queue. Alternatives like RQ, Dramatiq, and cloud-native solutions (AWS SQS, GCP Tasks) are equally valid choices.

from celery import Celery

app = Celery("tasks", broker="redis://localhost:6379")

@app.task
def send_email(to: str, subject: str, body: str) -> None:
    # This runs in a background worker
    email_client.send(to, subject, body)

# In your API handler
send_email.delay("user@example.com", "Welcome!", "Thanks for signing up")

Fundamental Patterns

Pattern 1: Return Job ID Immediately

For operations exceeding a few seconds, return a job ID and process asynchronously.

from uuid import uuid4
from dataclasses import dataclass
from enum import Enum
from datetime import datetime

class JobStatus(Enum):
    PENDING = "pending"
    RUNNING = "running"
    SUCCEEDED = "succeeded"
    FAILED = "failed"

@dataclass
class Job:
    id: str
    status: JobStatus
    created_at: datetime
    started_at: datetime | None = None
    completed_at: datetime | None = None
    result: dict | None = None
    error: str | None = None

# API endpoint
async def start_export(request: ExportRequest) -> JobResponse:
    """Start export job and return job ID."""
    job_id = str(uuid4())

    # Persist job record
    await jobs_repo.create(Job(
        id=job_id,
        status=JobStatus.PENDING,
        created_at=datetime.utcnow(),
    ))

    # Enqueue task for background processing
    await task_queue.enqueue(
        "export_data",
        job_id=job_id,
        params=request.model_dump(),
    )

    # Return immediately with job ID
    return JobResponse(
        job_id=job_id,
        status="pending",
        poll_url=f"/jobs/{job_id}",
    )

Pattern 2: Celery Task Configuration

Configure Celery tasks with proper retry and timeout settings.

from celery import Celery

app = Celery("tasks", broker="redis://localhost:6379")

# Global configuration
app.conf.update(
    task_time_limit=3600,          # Hard limit: 1 hour
    task_soft_time_limit=3000,      # Soft limit: 50 minutes
    task_acks_late=True,            # Acknowledge after completion
    task_reject_on_worker_lost=True,
    worker_prefetch_multiplier=1,   # Don't prefetch too many tasks
)

@app.task(
    bind=True,
    max_retries=3,
    default_retry_delay=60,
    autoretry_for=(ConnectionError, TimeoutError),
)
def process_payment(self, payment_id: str) -> dict:
    """Process payment with automatic retry on transient errors."""
    try:
        result = payment_gateway.charge(payment_id)
        return {"status": "success", "transaction_id": result.id}
    except PaymentDeclinedError as e:
        # Don't retry permanent failures
        return {"status": "declined", "reason": str(e)}
    except TransientError as e:
        # Retry with exponential backoff
        raise self.retry(exc=e, countdown=2 ** self.request.retries * 60)

Pattern 3: Make Tasks Idempotent

Workers may retry on crash or timeout. Design for safe re-execution.

@app.task(bind=True)
def process_order(self, order_id: str) -> None:
    """Process order idempotently."""
    order = orders_repo.get(order_id)

    # Already processed? Return early
    if order.status == OrderStatus.COMPLETED:
        logger.info("Order already processed", order_id=order_id)
        return

    # Already in progress? Check if we should continue
    if order.status == OrderStatus.PROCESSING:

…
अक्सर पूछे जाने वाले सवाल

'background task' क्या है?

यह ऐसा काम है जिसे आपके program को करना है, पर उसमें समय लग सकता है। इसे तुरंत करने के बजाय queue में रखा जाता है ताकि बाद में चलाया जा सके, और सामान्य उपयोग में रुकावट न आए।

अगर task fail हो जाए तो क्या होता है?

system task को अपने आप दोबारा चलाने की कोशिश कर सकता है। इसलिए ज़रूरी है कि task 'idempotent' हो, यानी उसे कई बार चलाने से भी कोई समस्या न हो।

मुझे task की स्थिति कैसे पता चले?

आमतौर पर task जमा करते समय आपको उसकी 'job ID' मिलती है। इस ID से आप system से पूछ सकते हैं कि task पूरा हुआ है, चल रहा है, या fail हो गया है।

जानकारी

लेखक का मूल विवरण

Python background job patterns including task queues, workers, and event-driven architecture. Use when implementing async task processing, job queues, long-running operations, or decoupling work from request/response cycles.

repo: wshobson/agents

लोकप्रियता

GitHub स्टार
41k
रैंकिंग में स्थान
#6757
लाइसेंस
MIT
अपडेट की गई
15/10/2026

क्या यह skill काम की है?

0

लॉग इन करें वोट करने के लिए।

कमेंट

  • …

इस repository की और skills

मिलती-जुलती skills