[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75G8DVH67G12HS38D7NWCGC":3,"skill-same:01M75G8DVH67G12HS38D7NWCGC":50},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M75G8DVH67G12HS38D7NWCGC","python-background-jobs",null,"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\u002Fresponse cycles.","RudyCity\u002Fsuperagent","RudyCity","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F82188919?v=4","01M75FP5X8AW8ACBH0SH34WS7M","01M75FP5YAHJK8M1Q52BWXB82K",70,"MIT","https:\u002F\u002Fgithub.com\u002FRudyCity\u002Fsuperagent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fpython-background-jobs\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: python-background-jobs\ndescription: 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\u002Fresponse cycles.\n---\n\n# Python Background Jobs & Task Queues\n\nDecouple long-running or unreliable work from request\u002Fresponse cycles. Return immediately to the user while background workers handle the heavy lifting asynchronously.\n\n## When to Use This Skill\n\n- Processing tasks that take longer than a few seconds\n- Sending emails, notifications, or webhooks\n- Generating reports or exporting data\n- Processing uploads or media transformations\n- Integrating with unreliable external services\n- Building event-driven architectures\n\n## Core Concepts\n\n### 1. Task Queue Pattern\n\nAPI accepts request, enqueues a job, returns immediately with a job ID. Workers process jobs asynchronously.\n\n### 2. Idempotency\n\nTasks may be retried on failure. Design for safe re-execution.\n\n### 3. Job State Machine\n\nJobs transition through states: pending → running → succeeded\u002Ffailed.\n\n### 4. At-Least-Once Delivery\n\nMost queues guarantee at-least-once delivery. Your code must handle duplicates.\n\n## Quick Start\n\nThis 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.\n\n```python\nfrom celery import Celery\n\napp = Celery(\"tasks\", broker=\"redis:\u002F\u002Flocalhost:6379\")\n\n@app.task\ndef send_email(to: str, subject: str, body: str) -> None:\n    # This runs in a background worker\n    email_client.send(to, subject, body)\n\n# In your API handler\nsend_email.delay(\"user@example.com\", \"Welcome!\", \"Thanks for signing up\")\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Return Job ID Immediately\n\nFor operations exceeding a few seconds, return a job ID and process asynchronously.\n\n```python\nfrom uuid import uuid4\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom datetime import datetime\n\nclass JobStatus(Enum):\n    PENDING = \"pending\"\n    RUNNING = \"running\"\n    SUCCEEDED = \"succeeded\"\n    FAILED = \"failed\"\n\n@dataclass\nclass Job:\n    id: str\n    status: JobStatus\n    created_at: datetime\n    started_at: datetime | None = None\n    completed_at: datetime | None = None\n    result: dict | None = None\n    error: str | None = None\n\n# API endpoint\nasync def start_export(request: ExportRequest) -> JobResponse:\n    \"\"\"Start export job and return job ID.\"\"\"\n    job_id = str(uuid4())\n\n    # Persist job record\n    await jobs_repo.create(Job(\n        id=job_id,\n        status=JobStatus.PENDING,\n        created_at=datetime.utcnow(),\n    ))\n\n    # Enqueue task for background processing\n    await task_queue.enqueue(\n        \"export_data\",\n        job_id=job_id,\n        params=request.model_dump(),\n    )\n\n    # Return immediately with job ID\n    return JobResponse(\n        job_id=job_id,\n        status=\"pending\",\n        poll_url=f\"\u002Fjobs\u002F{job_id}\",\n    )\n```\n\n### Pattern 2: Celery Task Configuration\n\nConfigure Celery tasks with proper retry and timeout settings.\n\n```python\nfrom celery import Celery\n\napp = Celery(\"tasks\", broker=\"redis:\u002F\u002Flocalhost:6379\")\n\n# Global configuration\napp.conf.update(\n    task_time_limit=3600,          # Hard limit: 1 hour\n    task_soft_time_limit=3000,      # Soft limit: 50 minutes\n    task_acks_late=True,            # Acknowledge after completion\n    task_reject_on_worker_lost=True,\n    worker_prefetch_multiplier=1,   # Don't prefetch too many tasks\n)\n\n@app.task(\n    bind=True,\n    max_retries=3,\n    default_retry_delay=60,\n    autoretry_for=(ConnectionError, TimeoutError),\n)\ndef process_payment(self, payment_id: str) -> dict:\n    \"\"\"Process payment with automatic retry on transient errors.\"\"\"\n    try:\n        result = payment_gateway.charge(payment_id)\n        return {\"status\": \"success\", \"transaction_id\": result.id}\n    except PaymentDeclinedError as e:\n        # Don't retry permanent failures\n        return {\"status\": \"declined\", \"reason\": str(e)}\n    except TransientError as e:\n        # Retry with exponential backoff\n        raise self.retry(exc=e, countdown=2 ** self.request.retries * 60)\n```\n\n### Pattern 3: Make Tasks Idempotent\n\nWorkers may retry on crash or timeout. Design for safe re-execution.\n\n```python\n@app.task(bind=True)\ndef process_order(self, order_id: str) -> None:\n    \"\"\"Process order idempotently.\"\"\"\n    order = orders_repo.get(order_id)\n\n    # Already processed? Return early\n    if order.status == OrderStatus.COMPLETED:\n        logger.info(\"Order already processed\", order_id=order_id)\n        return\n\n    # Already in progress? Check if we should continue\n    if order.status == OrderStatus.PROCESSING:\n        # Use idempotency key to avoid double-charging\n        pass\n\n    # Process with idempotency key\n    result = payment_provider.charge(\n        amount=order.total,\n        idempotency_key=f\"order-{order_id}\",  # Critical!\n    )\n\n    orders_repo.update(order_id, status=OrderStatus.COMPLETED)\n```\n\n**Idempotency Strategies:**\n\n1. **Check-before-write**: Verify state before action\n2. **Idempotency keys**: Use unique tokens with external services\n3. **Upsert patterns**: `INSERT ... ON CONFLICT UPDATE`\n4. **Deduplication window**: Track processed IDs for N hours\n\n### Pattern 4: Job State Management\n\nPersist job state transitions for visibility and debugging.\n\n```python\nclass JobRepository:\n    \"\"\"Repository for managing job state.\"\"\"\n\n    async def create(self, job: Job) -> Job:\n        \"\"\"Create new job record.\"\"\"\n        await self._db.execute(\n            \"\"\"INSERT INTO jobs (id, status, created_at)\n               VALUES ($1, $2, $3)\"\"\",\n            job.id, job.status.value, job.created_at,\n        )\n        return job\n\n    async def update_status(\n        self,\n        job_id: str,\n        status: JobStatus,\n        **fields,\n    ) -> None:\n        \"\"\"Update job status with timestamp.\"\"\"\n        updates = {\"status\": status.value, **fields}\n\n        if status == JobStatus.RUNNING:\n            updates[\"started_at\"] = datetime.utcnow()\n        elif status in (JobStatus.SUCCEEDED, JobStatus.FAILED):\n            updates[\"completed_at\"] = datetime.utcnow()\n\n        await self._db.execute(\n            \"UPDATE jobs SET status = $1, ... WHERE id = $2\",\n            updates, job_id,\n        )\n\n        logger.info(\n            \"Job status updated\",\n            job_id=job_id,\n            status=status.value,\n        )\n```\n\n## Detailed worked examples and patterns\n\nDetailed sections (starting with `## Advanced Patterns`) live in `references\u002Fdetails.md`. Read that file when the navigation summary above is insufficient.\n\n## Best Practices Summary\n\n1. **Return immediately** - Don't block requests for long operations\n2. **Persist job state** - Enable status polling and debugging\n3. **Make tasks idempotent** - Safe to retry on any failure\n4. **Use idempotency keys** - For external service calls\n5. **Set timeouts** - Both soft and hard limits\n6. **Implement DLQ** - Capture permanently failed tasks\n7. **Log transitions** - Track job state changes\n8. **Retry appropriately** - Exponential backoff for transient errors\n9. **Don't retry permanent failures** - Validation errors, invalid credentials\n10. **Monitor queue depth** - Alert on backlog growth\n","# Python Background Jobs & Task Queues\n\nDecouple long-running or unreliable work from request\u002Fresponse cycles. Return immediately to the user while background workers handle the heavy lifting asynchronously.\n\n## When to Use This Skill\n\n- Processing tasks that take longer than a few seconds\n- Sending emails, notifications, or webhooks\n- Generating reports or exporting data\n- Processing uploads or media transformations\n- Integrating with unreliable external services\n- Building event-driven architectures\n\n## Core Concepts\n\n### 1. Task Queue Pattern\n\nAPI accepts request, enqueues a job, returns immediately with a job ID. Workers process jobs asynchronously.\n\n### 2. Idempotency\n\nTasks may be retried on failure. Design for safe re-execution.\n\n### 3. Job State Machine\n\nJobs transition through states: pending → running → succeeded\u002Ffailed.\n\n### 4. At-Least-Once Delivery\n\nMost queues guarantee at-least-once delivery. Your code must handle duplicates.\n\n## Quick Start\n\nThis 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.\n\n```python\nfrom celery import Celery\n\napp = Celery(\"tasks\", broker=\"redis:\u002F\u002Flocalhost:6379\")\n\n@app.task\ndef send_email(to: str, subject: str, body: str) -> None:\n    # This runs in a background worker\n    email_client.send(to, subject, body)\n\n# In your API handler\nsend_email.delay(\"user@example.com\", \"Welcome!\", \"Thanks for signing up\")\n```\n\n## Fundamental Patterns\n\n### Pattern 1: Return Job ID Immediately\n\nFor operations exceeding a few seconds, return a job ID and process asynchronously.\n\n```python\nfrom uuid import uuid4\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom datetime import datetime\n\nclass JobStatus(Enum):\n    PENDING = \"pending\"\n    RUNNING = \"running\"\n    SUCCEEDED = \"succeeded\"\n    FAILED = \"failed\"\n\n@dataclass\nclass Job:\n    id: str\n    status: JobStatus\n    created_at: datetime\n    started_at: datetime | None = None\n    completed_at: datetime | None = None\n    result: dict | None = None\n    error: str | None = None\n\n# API endpoint\nasync def start_export(request: ExportRequest) -> JobResponse:\n    \"\"\"Start export job and return job ID.\"\"\"\n    job_id = str(uuid4())\n\n    # Persist job record\n    await jobs_repo.create(Job(\n        id=job_id,\n        status=JobStatus.PENDING,\n        created_at=datetime.utcnow(),\n    ))\n\n    # Enqueue task for background processing\n    await task_queue.enqueue(\n        \"export_data\",\n        job_id=job_id,\n        params=request.model_dump(),\n    )\n\n    # Return immediately with job ID\n    return JobResponse(\n        job_id=job_id,\n        status=\"pending\",\n        poll_url=f\"\u002Fjobs\u002F{job_id}\",\n    )\n```\n\n### Pattern 2: Celery Task Configuration\n\nConfigure Celery tasks with proper retry and timeout settings.\n\n```python\nfrom celery import Celery\n\napp = Celery(\"tasks\", broker=\"redis:\u002F\u002Flocalhost:6379\")\n\n# Global configuration\napp.conf.update(\n    task_time_limit=3600,          # Hard limit: 1 hour\n    task_soft_time_limit=3000,      # Soft limit: 50 minutes\n    task_acks_late=True,            # Acknowledge after completion\n    task_reject_on_worker_lost=True,\n    worker_prefetch_multiplier=1,   # Don't prefetch too many tasks\n)\n\n@app.task(\n    bind=True,\n    max_retries=3,\n    default_retry_delay=60,\n    autoretry_for=(ConnectionError, TimeoutError),\n)\ndef process_payment(self, payment_id: str) -> dict:\n    \"\"\"Process payment with automatic retry on transient errors.\"\"\"\n    try:\n        result = payment_gateway.charge(payment_id)\n        return {\"status\": \"success\", \"transaction_id\": result.id}\n    except PaymentDeclinedError as e:\n        # Don't retry permanent failures\n        return {\"status\": \"declined\", \"reason\": str(e)}\n    except TransientError as e:\n        # Retry with exponential backoff\n        raise self.retry(exc=e, countdown=2 ** self.request.retries * 60)\n```\n\n### Pattern 3: Make Tasks Idempotent\n\nWorkers may retry on crash or timeout. Design for safe re-execution.\n\n```python\n@app.task(bind=True)\ndef process_order(self, order_id: str) -> None:\n    \"\"\"Process order idempotently.\"\"\"\n    order = orders_repo.get(order_id)\n\n    # Already processed? Return early\n    if order.status == OrderStatus.COMPLETED:\n        logger.info(\"Order already processed\", order_id=order_id)\n        return\n\n    # Already in progress? Check if we should continue\n    if order.status == OrderStatus.PROCESSING:\n        # Use idempotency key to avoid double-charging\n        pass\n\n    # Process with idempotency key\n    result = payment_provider.charge(\n        amount=order.total,\n        idempotency_key=f\"order-{order_id}\",  # Critical!\n    )\n\n    orders_repo.update(order_id, status=OrderStatus.COMPLETED)\n```\n\n**Idempotency Strategies:**\n\n1. **Check-before-write**: Verify state before action\n2. **Idempotency keys**: Use unique tokens with external services\n3. **Upsert patterns**: `INSERT ... ON CONFLICT UPDATE`\n4. **Deduplication window**: Track processed IDs for N hours\n\n### Pattern 4: Job State Management\n\nPersist job state transitions for visibility and debugging.\n\n```python\nclass JobRepository:\n    \"\"\"Repository for managing job state.\"\"\"\n\n    async def create(self, job: Job) -> Job:\n        \"\"\"Create new job record.\"\"\"\n        await self._db.execute(\n            \"\"\"INSERT INTO jobs (id, status, created_at)\n               VALUES ($1, $2, $3)\"\"\",\n            job.id, job.status.value, job.created_at,\n        )\n        return job\n\n    async def update_status(\n        self,\n        job_id: str,\n        status: JobStatus,\n        **fields,\n    ) -> None:\n        \"\"\"Update job status with timestamp.\"\"\"\n        updates = {\"status\": status.value, **fields}\n\n        if status == JobStatus.RUNNING:\n            updates[\"started_at\"] = datetime.utcnow()\n        elif status in (JobStatus.SUCCEEDED, JobStatus.FAILED):\n            updates[\"completed_at\"] = datetime.utcnow()\n\n        await self._db.execute(\n            \"UPDATE jobs SET status = $1, ... WHERE id = $2\",\n            updates, job_id,\n        )\n\n        logger.info(\n            \"Job status updated\",\n            job_id=job_id,\n            status=status.value,\n        )\n```\n\n## Detailed worked examples and patterns\n\nDetailed sections (starting with `## Advanced Patterns`) live in `references\u002Fdetails.md`. Read that file when the navigation summary above is insufficient.\n\n## Best Practices Summary\n\n1. **Return immediately** - Don't block requests for long operations\n2. **Persist job state** - Enable status polling and debugging\n3. **Make tasks idempotent** - Safe to retry on any failure\n4. **Use idempotency keys** - For external service calls\n5. **Set timeouts** - Both soft and hard limits\n6. **Implement DLQ** - Capture permanently failed tasks\n7. **Log transitions** - Track job state changes\n8. **Retry appropriately** - Exponential backoff for transient errors\n9. **Don't retry permanent failures** - Validation errors, invalid credentials\n10. **Monitor queue depth** - Alert on backlog growth\n",{"name":5,"description":7},"main","62c7af5ced2c21355d148c243edb6d5921cca1a6",".agents\u002Fskills\u002Fpython-background-jobs",8,"https:\u002F\u002Fgithub.com\u002FRudyCity\u002Fsuperagent","https:\u002F\u002Fgithub.com\u002FRudyCity","2026-11-14 22:58:49",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add RudyCity\u002Fsuperagent --skill python-background-jobs",{"tool":36,"command":37},"bunx","bunx skills add RudyCity\u002Fsuperagent --skill python-background-jobs",{"tool":39,"command":40},"pnpm","pnpm dlx skills add RudyCity\u002Fsuperagent --skill python-background-jobs","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FRudyCity\u002Fsuperagent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fpython-background-jobs\u002FSKILL.md",true,[44],{"path":45,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":48,"sourceHtmlUrl":49},"references\u002Fdetails.md","REFERENCE","参考文档",3429,"https:\u002F\u002Fgithub.com\u002FRudyCity\u002Fsuperagent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fpython-background-jobs\u002Freferences\u002Fdetails.md",[51,58,65,72,79,86],{"skillNo":52,"name":53,"nameZh":6,"description":54,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":55,"categories":56,"keywords":57,"publishedAt":18},"01M75GP28CM6QCSXSHKFF3NNKS","telegram_bot","Use Telegram Bot when the user asks for Telegram Bot or this provider's API.","https:\u002F\u002Fgithub.com\u002FRudyCity\u002Fsuperagent\u002Fblob\u002Fmain\u002Fmuse-bridge-kit\u002Fskills\u002Ftelegram-bot\u002FSKILL.md",[],[],{"skillNo":59,"name":60,"nameZh":6,"description":61,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":62,"categories":63,"keywords":64,"publishedAt":18},"01M75GNZGZYM7NWDV6MBP3HS14","superagent-bridge","Operate the Muse\u003C->superagent Telegram bridge: poll the private group for task_request\u002Ftask_result envelopes, validate senders, and reply with task_batch\u002Ftask_done as Muse (the remote brain).","https:\u002F\u002Fgithub.com\u002FRudyCity\u002Fsuperagent\u002Fblob\u002Fmain\u002Fmuse-bridge-kit\u002Fskills\u002Fsuperagent-bridge\u002FSKILL.md",[],[],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":18},"01M75GNHN19HJWZ7NAPM5E5JCV","Writing Skills","TDD for process documentation - test with subagents before writing, iterate until bulletproof","https:\u002F\u002Fgithub.com\u002FRudyCity\u002Fsuperagent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwriting-skills\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":18},"01M75GNCQEKVRA4FH161NZPZNB","writing-shape","Take a markdown file of raw material and shape it into an article through a conversational session — drafting candidate openings, growing the piece paragraph by paragraph, arguing about format (lists, tables, callouts, quotes) at each step. Use when the user has a pile of notes, fragments, or a rough draft and wants help turning it into something publishable.","https:\u002F\u002Fgithub.com\u002FRudyCity\u002Fsuperagent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwriting-shape\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M75GNAF9NAYCSTBDZDGMK0DZ","Writing Plans","Create detailed implementation plans with bite-sized tasks for engineers with zero codebase context","https:\u002F\u002Fgithub.com\u002FRudyCity\u002Fsuperagent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwriting-plans\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":18},"01M75GN72EV0V5NQAW9CSPFRFH","writing-guidelines","Review docs\u002Fprose for Writing Guidelines compliance. Use when asked to \"review my docs\", \"check writing style\", \"audit prose\", \"review docs voice and tone\", or \"check this page against the writing handbook\".","https:\u002F\u002Fgithub.com\u002FRudyCity\u002Fsuperagent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwriting-guidelines\u002FSKILL.md",[],[]]