Celery Patterns 标志

Celery Patterns

社区
manikosto
celery-patterns

分布式任务队列的 Celery 模式——任务定义、重试策略、调度、链式任务/组任务、监控,以及使用 Redis/RabbitMQ 进行生产环境配置。

概览

发布者manikosto
代码仓库claude-code-python-stack
技能名称celery-patterns
星标数
54
复刻数
10
附带文件
仅含指令
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 manikosto 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Celery Patterns AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/manikosto/claude-code-python-stack/tree/main/skills/celery-patterns
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/manikosto/claude-code-python-stack.git /tmp/claude-code-python-stack
mkdir -p .claude/skills
cp -r /tmp/claude-code-python-stack/skills/celery-patterns .claude/skills/celery-patterns
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Celery Patterns,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Celery Patterns。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Celery Patterns 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Celery Patterns

Distributed task queue patterns for Python applications.

When to Activate

  • Offloading long-running tasks (email, PDF generation, data processing)
  • Scheduling periodic tasks (cron-like)
  • Building data processing pipelines
  • Implementing retry logic for external API calls
  • Setting up task monitoring and alerting

Setup

Configuration

python
# config/celery.py
from celery import Celery
from app.config import settings

celery_app = Celery(
    "worker",
    broker=settings.REDIS_URL,
    backend=settings.REDIS_URL,
)

celery_app.conf.update(
    task_serializer="json",
    accept_content=["json"],
    result_serializer="json",
    timezone="UTC",
    enable_utc=True,
    task_track_started=True,
    task_time_limit=300,           # Hard limit: 5 minutes
    task_soft_time_limit=240,      # Soft limit: 4 minutes
    worker_prefetch_multiplier=1,  # Disable prefetching for fair scheduling
    worker_max_tasks_per_child=1000,  # Restart worker after 1000 tasks (memory leak protection)
    task_acks_late=True,           # Acknowledge after execution (at-least-once)
    task_reject_on_worker_lost=True,
    result_expires=3600,           # Results expire after 1 hour
)

# Auto-discover tasks in all apps
celery_app.autodiscover_tasks(["app.tasks"])

Django Integration

python
# config/celery.py (Django)
import os
from celery import Celery

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.production")

app = Celery("myproject")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()

# config/__init__.py
from .celery import app as celery_app
__all__ = ("celery_app",)

Task Definitions

Basic Task

python
from celery import shared_task

@shared_task
def send_email(to: str, subject: str, body: str) -> dict:
    """Send email task."""
    result = email_service.send(to=to, subject=subject, body=body)
    return {"status": "sent", "message_id": result.id}

# Call the task
send_email.delay("user@example.com", "Welcome!", "Hello there")

# Or with more control
send_email.apply_async(
    args=["user@example.com", "Welcome!", "Hello there"],
    countdown=60,          # Delay execution by 60 seconds
    expires=3600,          # Task expires after 1 hour if not started
    queue="emails",        # Route to specific queue
)

Task with Retry

python
@shared_task(
    bind=True,
    max_retries=3,
    default_retry_delay=60,  # 60 seconds between retries
    autoretry_for=(ConnectionError, TimeoutError),
    retry_backoff=True,      # Exponential backoff
    retry_backoff_max=600,   # Max 10 minutes between retries
    retry_jitter=True,       # Add random jitter
)
def call_external_api(self, url: str, payload: dict) -> dict:
    """Call external API with automatic retry on failure."""
    try:
        response = httpx.post(url, json=payload, timeout=30)
        response.raise_for_status()
        return response.json()
    except httpx.HTTPStatusError as exc:
        if exc.response.status_code >= 500:
            raise self.retry(exc=exc)
        raise  # Don't retry 4xx errors

Task with Custom Retry

python
@shared_task(bind=True, max_retries=5)
def process_payment(self, order_id: int) -> dict:
    """Process payment with custom retry logic."""
    try:
        order = Order.objects.get(id=order_id)
        result = payment_gateway.charge(order)
        order.status = "paid"
        order.save()
        return {"order_id": order_id, "status": "paid"}
    except PaymentDeclinedError:
        order.status = "declined"
        order.save()
        return {"order_id": order_id, "status": "declined"}
    except PaymentGatewayError as exc:
        raise self.retry(
            exc=exc,
            countdown=2 ** self.request.retries * 30,  # 30s, 60s, 120s, 240s, 480s
        )

Task with Progress Tracking

python
@shared_task(bind=True)
def process_large_file(self, file_path: str) -> dict:
    """Process file with progress updates."""
    total_lines = count_lines(file_path)
    processed = 0

    with open(file_path) as f:
        for line in f:
            process_line(line)
            processed += 1

            if processed % 1000 == 0:
                self.update_state(
                    state="PROGRESS",
                    meta={"current": processed, "total": total_lines, "percent": processed / total_lines * 100},
                )

    return {"processed": processed, "total": total_lines}

# Check progress
result = process_large_file.AsyncResult(task_id)
if result.state == "PROGRESS":
    print(f"Progress: {result.info['percent']:.1f}%")

Task Chains and Groups

Chain (Sequential)

python
from celery import chain

# Tasks execute sequentially, result passes to next
workflow = chain(
    fetch_data.s(url),
    transform_data.s(),
    save_to_database.s(),
    send_notification.s(),
)
result = workflow.apply_async()

Group (Parallel)

python
from celery import group

# Tasks execute in parallel
job = group([
    process_chunk.s(chunk) for chunk in data_chunks
])
result = job.apply_async()

# Wait for all results
results = result.get(timeout=300)

Chord (Group + Callback)

python
from celery import chord

# Run group in parallel, then call callback with results
workflow = chord(
    [process_chunk.s(chunk) for chunk in data_chunks],
    aggregate_results.s(),
)
result = workflow.apply_async()

Canvas Example

python
from celery import chain, group, chord

# Complex workflow
workflow = chain(
    fetch_raw_data.s(source_id),
    group([
        process_text.s(),
        process_images.s(),
        process_metadata.s(),
    ]),
    merge_results.s(),
    save_and_notify.s(user_id),
)

Periodic Tasks (Beat)

python
from celery.schedules import crontab

celery_app.conf.beat_schedule = {
    "cleanup-expired-sessions": {
        "task": "app.tasks.cleanup_expired_sessions",
        "schedule": crontab(hour=2, minute=0),  # Daily at 2 AM
    },
    "send-daily-report": {
        "task": "app.tasks.send_daily_report",
        "schedule": crontab(hour=8, minute=0, day_of_week="mon-fri"),
    },
    "check-payment-status": {
        "task": "app.tasks.check_pending_payments",
        "schedule": 300.0,  # Every 5 minutes
    },
    "monthly-invoice": {
        "task": "app.tasks.generate_invoices",
        "schedule": crontab(day_of_month=1, hour=0, minute=0),
    },
}

Task Routing

python
celery_app.conf.task_routes = {
    "app.tasks.send_email": {"queue": "emails"},
    "app.tasks.process_payment": {"queue": "payments", "priority": 9},
    "app.tasks.generate_report": {"queue": "reports"},
    "app.tasks.*": {"queue": "default"},
}

# Start workers for specific queues
# celery -A config worker -Q emails -c 4
# celery -A config worker -Q payments -c 2
# celery -A config worker -Q default,reports -c 8

Error Handling

python
from celery import shared_task
from celery.exceptions import SoftTimeLimitExceeded

@shared_task(bind=True, soft_time_limit=120, time_limit=150)
def long_running_task(self, data: dict) -> dict:
    try:
        result = process(data)
        return result
    except SoftTimeLimitExceeded:
        # Graceful shutdown: save progress, cleanup
        save_partial_progress(self.request.id, data)
        return {"status": "timeout", "partial": True}

# Global error handler
@celery_app.task(bind=True)
def on_task_failure(self, exc, task_id, args, kwargs, einfo):
    """Handle task failures globally."""
    logger.error(f"Task {task_id} failed: {exc}", exc_info=einfo)
    notify_ops_team(task_id, str(exc))

Testing

python
import pytest
from unittest.mock import patch

# Test task logic directly (no Celery overhead)
def test_send_email():
    with patch("app.tasks.email_service.send") as mock_send:
        mock_send.return_value.id = "msg-123"
        result = send_email("test@example.com", "Subject", "Body")
        assert result["status"] == "sent"
        mock_send.assert_called_once()

# Test with eager mode
@pytest.fixture(autouse=True)
def celery_eager(settings):
    settings.CELERY_TASK_ALWAYS_EAGER = True
    settings.CELERY_TASK_EAGER_PROPAGATES = True

def test_task_chain():
    result = chain(fetch_data.s("url"), transform_data.s()).apply()
    assert result.successful()

Monitoring

bash
# Flower (web UI)
pip install flower
celery -A config flower --port=5555

# CLI monitoring
celery -A config inspect active          # Active tasks
celery -A config inspect reserved        # Queued tasks
celery -A config inspect stats           # Worker stats
celery -A config inspect ping            # Worker health
celery -A config purge                   # Clear queues (DANGEROUS)

Production Commands

bash
# Start worker
celery -A config worker --loglevel=info --concurrency=8

# Start beat scheduler
celery -A config beat --loglevel=info

# Combined (dev only)
celery -A config worker --beat --loglevel=info

# With supervisor (production)
# /etc/supervisor/conf.d/celery.conf
[program:celery-worker]
command=celery -A config worker -l info -c 8
directory=/app
user=appuser
autostart=true
autorestart=true
stopwaitsecs=600

Quick Reference

PatternUsage
task.delay(*args)Fire and forget
task.apply_async(kwargs=...)Full control
chain(a.s(), b.s())Sequential execution
group([a.s(x) for x in items])Parallel execution
chord(group, callback)Parallel + aggregate
bind=TrueAccess self for retries
autoretry_for=(Error,)Auto-retry on exceptions
retry_backoff=TrueExponential backoff
self.update_state()Progress tracking
beat_schedulePeriodic tasks

Remember: Tasks should be idempotent (safe to run multiple times with same input). Use task_acks_late=True for at-least-once delivery. Never pass large objects as task arguments -- pass IDs and fetch from DB.

常见问题

Celery Patterns AI 技能有什么作用?

分布式任务队列的 Celery 模式——任务定义、重试策略、调度、链式任务/组任务、监控,以及使用 Redis/RabbitMQ 进行生产环境配置。

为什么在 TypingMind 中使用 Celery Patterns?

因为您只需安装一次,就能搭配任何模型使用。Celery Patterns 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Celery Patterns?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/manikosto/claude-code-python-stack/tree/main/skills/celery-patterns。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Celery Patterns?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Celery Patterns 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Celery Patterns 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Celery Patterns AI 技能免费吗?

manikosto 已在 GitHub 上发布了该技能。请查看代码仓库了解许可条款。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇