惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 聂微东
Forbes - Security
Forbes - Security
IT之家
IT之家
P
Privacy International News Feed
宝玉的分享
宝玉的分享
小众软件
小众软件
Google DeepMind News
Google DeepMind News
美团技术团队
G
GRAHAM CLULEY
T
Tor Project blog
Recorded Future
Recorded Future
I
Intezer
C
Cyber Attacks, Cyber Crime and Cyber Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The Hacker News
The Hacker News
Hugging Face - Blog
Hugging Face - Blog
A
About on SuperTechFans
Scott Helme
Scott Helme
WordPress大学
WordPress大学
F
Full Disclosure
D
Docker
G
Google Developers Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Cyberwarzone
Cyberwarzone
The Last Watchdog
The Last Watchdog
V
V2EX
www.infosecurity-magazine.com
www.infosecurity-magazine.com
NISL@THU
NISL@THU
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Security Latest
Security Latest
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Recent Announcements
Recent Announcements
P
Palo Alto Networks Blog
L
LINUX DO - 热门话题
V
Visual Studio Blog
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog
博客园 - 叶小钗
N
Netflix TechBlog - Medium
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
量子位
腾讯CDC
H
Heimdal Security Blog
博客园 - 【当耐特】
Simon Willison's Weblog
Simon Willison's Weblog
P
Privacy & Cybersecurity Law Blog
S
Securelist
Vercel News
Vercel News
J
Java Code Geeks

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Cron jobs sin Celery, sin Redis, sin Beat: cómo Fitz mete un scheduler distribuido adentro del lenguaje
Martin Palopoli · 2026-06-23 · via DEV Community

Para correr una task cada 5 minutos en Python necesitás Celery + Redis + Celery Beat + worker process + Dockerfile dedicado. En Fitz es un decorador. Con retry, timezone, persistencia y catch-up adentro del lenguaje.

La historia de siempre

Tu cliente está contento con la API. Está corriendo. Entonces te pide tres cosas:

  1. "¿Podemos limpiar sesiones vencidas cada noche?"
  2. "¿Podés mandar el email de bienvenida en background así el signup no espera?"
  3. "El reporte diario tiene que correr a las 9 AM hora de Buenos Aires."

Tres pedidos chicos. Si estás en Python, la respuesta honesta es: "ok, dame dos días para meter Celery."

El stack típico de Python

pip install celery redis

celery_app.py:

from celery import Celery
from celery.schedules import crontab

celery_app = Celery(
    "myapp",
    broker="redis://redis:6379/0",
    backend="redis://redis:6379/1",
)

celery_app.conf.beat_schedule = {
    "cleanup-sessions-nightly": {
        "task": "myapp.tasks.cleanup_old_sessions",
        "schedule": crontab(hour=3, minute=0),
    },
    "daily-report": {
        "task": "myapp.tasks.generate_daily_report",
        "schedule": crontab(hour=12, minute=0),  # 9am Buenos Aires = 12:00 UTC
        # ojo: si DST cambia, esto te llega tarde
    },
}
celery_app.conf.timezone = "UTC"

tasks.py:

from .celery_app import celery_app
from .db import get_session

@celery_app.task(autoretry_for=(Exception,), retry_backoff=True, max_retries=3)
def cleanup_old_sessions():
    with get_session() as s:
        s.execute("DELETE FROM sessions WHERE expires_at < now()")
        s.commit()

@celery_app.task(autoretry_for=(SMTPError,), retry_backoff=True, max_retries=5)
def send_welcome_email(email: str):
    smtp.send(email, "Welcome!")

api.py:

@app.post("/signup")
def signup(creds: Credentials):
    user = create_user(creds)
    send_welcome_email.delay(user.email)  # fire-and-forget vía broker
    return user

docker-compose.yml:

services:
  api:
    build: .
    command: uvicorn api:app --host 0.0.0.0
  celery-worker:
    build: .
    command: celery -A celery_app worker --loglevel=info
    depends_on: [redis]
  celery-beat:
    build: .
    command: celery -A celery_app beat --loglevel=info
    depends_on: [redis]
  redis:
    image: redis:7-alpine

Mas:

  • Un supervisord.conf o systemd unit que mantenga viva la cosa cuando crashee.
  • (Opcional) flower para visibility — 4to proceso.
  • Conversiones de timezone hechas a mano (Celery beat trabaja en UTC, vos tenés que calcular el offset).
  • Cuando el worker crashea entre que pegó al broker y completó la task: ¿se reintenta? ¿queda colgada? Depende de cómo te configuraste el acks_late y task_reject_on_worker_lost.

Cuatro procesos en producción. Tres librerías nuevas. Un broker. Convenciones nuevas. Un día de setup.

Lo mismo en Fitz

@cron("0 3 * * *", tz="UTC")
async fn cleanup_old_sessions(db: DbConn) {
    db.exec("DELETE FROM sessions WHERE expires_at < now()").await
}

@cron("0 9 * * *", tz="America/Argentina/Buenos_Aires")
async fn daily_report(db: DbConn) {
    // ...
}

@background
async fn send_welcome_email(email: Str) {
    // cosa cara
}

@post("/signup")
fn signup(creds: Credentials) -> User {
    let user = create_user(creds)
    spawn(send_welcome_email(user.email))  // fire-and-forget tipado
    return user
}

docker-compose.yml:

services:
  api:
    build: .

Eso es todo. Un binario. Un proceso. Sin broker. Sin worker dedicado. Sin beat. El scheduler corre adentro del proceso de Fitz.

La tabla cruda

Item Python (Celery + Redis + Beat) Fitz
Setup inicial 4 archivos + 3 servicios + 1 broker 1 decorador
Schedule crontab(hour=3, minute=0) en config @cron("0 3 * * *")
Timezone UTC + offset manual tz="America/Argentina/Buenos_Aires"
Retry/backoff autoretry_for=(...) + retry_backoff=True retry={max=3, backoff="exponential", initial_secs=1, max_secs=30}
Persistencia de runs Redis result backend + visualización con Flower store=db, tabla auto-creada en Postgres
Catch-up de runs perdidos No nativo catch_up=true
Background fire-and-forget .delay(arg) con broker spawn(fn_call) directo
Type checking de args Ninguno (todo serializado vía JSON) Static —spawn exige @background y refina a Future<T>
Procesos en prod api + worker + beat + redis api
Imagen Docker 3 (api, worker, beat) + redis 1

Persistencia opt-in con store=db

Cuando querés history de runs para auditoría:

@cron("0 3 * * *", store=db, retry={max=3, backoff="exponential"})
async fn cleanup_old_sessions(db: DbConn) {
    db.exec("DELETE FROM sessions WHERE expires_at < now()").await
}

Al boot, Fitz crea (si no existe) fitz_cron_jobs y fitz_cron_runs. Cada attempt queda persistida con started_at/finished_at/status/attempt/error. Lo consultás con SQL plano:

SELECT job_name, status, attempt, error, started_at
FROM fitz_cron_runs
WHERE started_at > now() - interval '24 hours'
ORDER BY started_at DESC;

Sin instalar Flower. Sin webhook para Sentry. Tu DB que ya tenés.

Catch-up

Si el binario estuvo caído entre las 3 AM y las 7 AM y el cron era a las 3:

  • Celery beat: la oportunidad se pierde. La task no se vuelve a disparar hasta la próxima medianoche siguiente.
  • Fitz con catch_up=true: al boot, calcula que hubo un run perdido entre last_run_at y now, ejecuta UN run inmediato (no N — evita spam), y vuelve al schedule normal.
@cron("0 3 * * *", store=db, catch_up=true)
async fn cleanup_old_sessions(db: DbConn) { ... }

Retry con backoff configurable

Tres modos de backoff: exponential (1s, 2s, 4s, 8s...), linear (1s, 2s, 3s, 4s...), constant (1s, 1s, 1s...). Con cap max_secs:

@cron("*/10 * * * *",
    retry={ max=5, backoff="exponential", initial_secs=1, max_secs=60 })
async fn sync_external_api(db: DbConn) {
    // 1s → 2s → 4s → 8s → 16s (capeado a 60s si llegara más alto)
}

En Python con Celery:

@celery_app.task(
    autoretry_for=(ConnectionError, TimeoutError),
    retry_backoff=True,
    retry_backoff_max=60,
    retry_jitter=False,
    max_retries=5,
)
def sync_external_api():
    ...

Equivalente. Pero notá que Celery tenés que enumerar las excepciones que disparan retry, y el backoff es un bool en lugar de un kind enum. Fitz hace retry ante cualquier error que devuelva la fn (consistente con el modelo Result del lenguaje), y el modo de backoff es explícito.

Timezone real, no offset hardcoded

Las DST changes son el bug que te despiertan a las 4 AM. Celery beat trabaja en UTC y vos tenés que recordar que entre marzo y noviembre tu cron de las 9 AM Buenos Aires se corre a las 12 UTC, pero el resto del año cambia. Tu cliente está en otro huso. Tu app vende a tres países más.

Fitz acepta IANA timezones directamente:

@cron("0 9 * * *", tz="America/Argentina/Buenos_Aires") async fn buenos_aires() { ... }
@cron("0 9 * * *", tz="America/New_York")              async fn new_york()      { ... }
@cron("0 9 * * *", tz="Asia/Tokyo")                    async fn tokyo()         { ... }

Cada uno corre a las 9 AM local de su tz, con DST manejado por la lib subyacente (chrono-tz). No conversiones a mano.

Background jobs sin broker

# Python
@app.post("/signup")
def signup(creds: Credentials):
    user = create_user(creds)
    send_welcome_email.delay(user.email)  # serializa args → Redis → worker
    return user

// Fitz
@background
async fn send_welcome_email(email: Str) {
    smtp.send(email, "Welcome!")
}

@post("/signup")
fn signup(creds: Credentials) -> User {
    let user = create_user(creds)
    spawn(send_welcome_email(user.email))  // tokio::spawn nativo, tipado
    return user
}

El compilador exige que la fn esté decorada con @background para autorizar el spawn(...) — sin esto, el callsite tira error de tipo en build time. Y refina el retorno a Future<Null> con el tipo concreto del target, no Any. Si send_welcome_email retorna Result<()>, el spawn(...) te lo da tipado.

¿Cuándo NO usar @background y volver a Celery?

  • Si necesitás que los jobs sobrevivan crashes del proceso → persistencia explícita con store=db cubre cron jobs; para @background con persistencia es deuda residual.
  • Si necesitás distribuir jobs en N workers en N nodos → Celery con un broker compartido sigue siendo la respuesta. @background corre en el proceso.

Para el 90% de servicios (cleanup nocturno, email transaccional, recálculo de KPIs, sync de cache) el modelo de Fitz alcanza y sobra.

Cron-only mode para systemd

Para servicios que SOLO tienen jobs (sin HTTP), fitz build produce un binario que arranca el scheduler y bloquea con ctrl+c:

@cron("0 3 * * *") async fn cleanup() { ... }
@cron("*/15 * * * *") async fn sync() { ... }

Como systemd unit:

[Unit]
Description=Scheduled jobs for myapp
After=network.target

[Service]
ExecStart=/usr/local/bin/myapp-jobs
Restart=always
User=myapp

[Install]
WantedBy=multi-user.target

Cero brokers. El binario es 5 MB. systemctl restart myapp-jobs y listo.

Paridad bit-a-bit fitz runfitz build

Esto es lo que vuelve esto entregable: el binario que producís con fitz build ejecuta el mismo scheduler que fitz run, con el mismo cron expression parser, los mismos retries, la misma timezone. Misma sintaxis, mismas semánticas, sin "ah esto solo funciona en producción si configurás Celery".

Lo que Fitz NO te da (todavía)

Soy honesto sobre dónde no llega:

  • Distribuir jobs en N workers/nodos compartiendo cola. @cron corre en el proceso. Si corrés dos binarios con el mismo @cron, ambos disparan — bug, no feature. Para horizontal scaling de jobs, sigue siendo Celery (o NATS JetStream, o Temporal). Hay deuda explícita en el roadmap sobre locks distribuidos.
  • UI tipo Flower. Los datos están en fitz_cron_jobs y fitz_cron_runs. Si querés dashboards, dashboards externos (Grafana, Metabase) cubren.
  • @background con persistencia entre restarts. Para @cron está en v0.11.2 (cierre 9.w.3.iter2). Para @background arranca el spawn pero no sobrevive crash — diferido a iter3 si entra demanda.
  • Cancelación de jobs en flight. Hoy no hay API para "cancelar todos los runs en cola de X job". El proceso muere → los runs en flight mueren con él.

Si estás en uno de esos casos, Fitz no es la herramienta hoy. Si no, el modelo de un solo binario cubre el caso real con menos partes móviles.

Cierre

El argumento para sumar Celery a una API en Python típicamente es: "pero después escala mejor." En el 90% de los servicios que escribí en la última década, ese "después" nunca llegó — la app pasó toda su vida útil con menos de 100 jobs por hora y nunca necesitó un cluster de workers.

Para ese 90%, Fitz reemplaza 4 procesos + 3 librerías + 1 broker con un decorador. Cuando llegues al otro 10% donde necesitás scaling horizontal real, Celery sigue ahí — from python import celery también está disponible, podés hacerlo tú mismo.

Pero arrancar el proyecto con el modelo más simple posible y subir la complejidad solo cuando lo necesitás es el ciclo de feedback que Fitz quiere darte.


Próximo post de la serie: "Auth con JWT, RBAC y token blacklist sin pegar 5 librerías: Fitz vs FastAPI + python-jose + passlib + Redis blacklist" — el flow completo de auth, lado a lado.

Repo: github.com/Thegreekman76/fitz
Capítulo 30 de la guía (Jobs sin Celery): docs/guide.md