本文へスキップ
Skillpedia
APIとサーバー(バックエンド)41k · #6757

python-background-jobs

できること

このスキルは、一斉メール送信やレポート生成のように、完了までに時間がかかる処理を整理するのに役立ちます。重い処理をバックグラウンドで行うことで、プログラムはユーザーへの応答を素早く続けられます。

使う場面

  • ✓大量のメールを一度に送信するとき。
  • ✓作成に時間がかかる大きなレポートを生成するとき。
  • ✓時間のかかるファイルのアップロード処理を行うとき。

スキルのリンク

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

コピーしてAI(Claude、ChatGPT、Cursor)に貼り付け、指示に従うよう頼んでください。

使い方

いちばん簡単な方法:メッセージをコピーしてAIに貼り付けるだけ。AIがスキルを読んで指示に従います。

貼り付け用メッセージ

このスキルを使って手伝ってください:https://github.com/wshobson/agents/blob/main/plugins/python-development/skills/python-background-jobs/SKILL.md このリンクのSKILL.mdファイルを読んで、私の作業でその指示に従ってください。
こういうスキルを、AIが自分で見つけてくれたら?無料のSkillpedia MCPをインストール。1行で、作業の前に15,000+のスキルから探してくれます。1分でインストール →

AIへの頼み方の例

“プログラムを止めずに、1000人にメールを送信するにはどうすればよいですか?”

毎週5つの新しいスキル。1分で読めます。

仕組み

プログラムは処理を「タスク」としてキューに送ります。別の「ワーカー」がそのタスクを受け取って実行します。これによりメインのプログラムは、止まることなく応答を続けられます。

技術的な内容(元の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:

…
よくある質問

「バックグラウンドタスク」とは何ですか?

プログラムが実行する必要はあるものの、完了までに時間がかかる可能性のある処理のことです。すぐに実行する代わりにキューに入れておき、通常の操作を妨げないように、あとで実行されます。

タスクが失敗した場合はどうなりますか?

システムが自動的にタスクを再実行することがあります。そのため、タスクが「冪等(べきとう)」であることが重要です。つまり、何度実行しても問題が起きないようになっている必要があります。

タスクの状態はどうすればわかりますか?

通常、タスクを送信すると、そのタスク用の「ジョブID」が届きます。このIDを使えば、タスクが完了したか、実行中か、失敗したかをシステムに問い合わせられます。

詳細

作者による元の説明

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
更新日
2026/10/15

このスキルは役に立ちますか?

0

ログイン して投票しましょう。

コメント

  • …

このリポジトリの他のスキル

似ているスキル