0Pricing
Supabase Backend as a Service · Lección

Programación de tareas recurrentes con pg_cron

Automatice tareas recurrentes dentro de Supabase usando pg_cron para programar llamadas periódicas a Edge Functions, tareas de limpieza y procesos de agregación de datos con un calendario fiable.

Programación de tareas recurrentes con pg_cron es una lección gratuita de Supabase Backend as a Service en CoddyKit. Esta es la lección 3 de 3. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Supabase Backend as a Service, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Supabase Backend as a Service incluye 3 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

Why Scheduled Jobs Matter

Complex workflows often need work to happen on a schedule, not just in response to a request. Think nightly cleanups, hourly aggregations, or weekly digest emails.

Supabase ships with the pg_cron extension, letting you run SQL on a recurring timetable directly inside Postgres.

  • No external scheduler to maintain
  • Runs close to your data
  • Can trigger Edge Functions via HTTP

Enabling pg_cron

Enable the extension once per project. In the Supabase dashboard go to Database > Extensions and toggle pg_cron, or run SQL.

It creates a cron.job table that tracks every scheduled task.

create extension if not exists pg_cron;

Anatomy of a Cron Schedule

pg_cron uses standard 5-field cron syntax: minute, hour, day-of-month, month, day-of-week.

  • 0 3 * * * = every day at 03:00
  • */15 * * * * = every 15 minutes
  • 0 0 * * 0 = every Sunday at midnight

Scheduling Your First Job

Use cron.schedule(name, schedule, sql) to register a job. Here we delete expired sessions every night at 2 AM.

select cron.schedule(
  'nightly-session-cleanup',
  '0 2 * * *',
  $$ delete from sessions where expires_at < now() $$
);

Inspecting Scheduled Jobs

Every job lives in cron.job. Query it to confirm your schedule and find the jobid you will need for updates or removal.

select jobid, schedule, jobname, active from cron.job;

Reviewing Run History

pg_cron records each execution in cron.job_run_details. This is your first stop for debugging a job that did not do what you expected.

  • status shows success or failure
  • return_message carries any error text
select jobid, status, return_message, start_time
from cron.job_run_details
order by start_time desc
limit 10;

Triggering an Edge Function from Cron

For real workflow logic, call an Edge Function via HTTP using the pg_net extension. The cron job fires the request; the function does the heavy lifting.

select cron.schedule(
  'hourly-digest',
  '0 * * * *',
  $$ select net.http_post(
       url := 'https://your-project.functions.supabase.co/digest',
       headers := '{"Authorization": "Bearer SERVICE_ROLE_KEY"}'::jsonb
     ) $$
);

Updating a Job

To change a schedule, simply call cron.schedule again with the same job name. pg_cron replaces the existing definition rather than creating a duplicate.

select cron.schedule(
  'nightly-session-cleanup',
  '0 4 * * *',
  $$ delete from sessions where expires_at < now() $$
);

Unscheduling a Job

Remove a job by name with cron.unschedule. Always clean up jobs you no longer need so run history stays meaningful.

select cron.unschedule('nightly-session-cleanup');

Idempotency and Overlap

Scheduled jobs can overlap if one run takes longer than its interval. Design jobs to be idempotent and guard against concurrent runs.

  • Use advisory locks for long jobs
  • Process in bounded batches
  • Mark rows as processed before acting

Timezone Awareness

pg_cron schedules run in the database server timezone, typically UTC. A job set for 0 0 * * * fires at UTC midnight, not your local midnight.

Compute local-time offsets explicitly so reports land when users expect them.

Quick Check

Test your understanding of pg_cron scheduling.

Recap

You can now automate recurring workflow steps inside Supabase.

  • Enable pg_cron and use 5-field cron syntax
  • Schedule with cron.schedule, remove with cron.unschedule
  • Trigger Edge Functions via net.http_post
  • Audit runs in cron.job_run_details
  • Account for UTC timezone and overlapping runs

Preguntas frecuentes

¿La lección «Programación de tareas recurrentes con pg_cron» es gratis?

Sí — el texto completo de «Programación de tareas recurrentes con pg_cron» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Supabase Backend as a Service, actualiza a CoddyKit PRO. El curso de Supabase Backend as a Service incluye 3 lecciones en total.

¿Qué aprenderé en «Programación de tareas recurrentes con pg_cron»?

Automatice tareas recurrentes dentro de Supabase usando pg_cron para programar llamadas periódicas a Edge Functions, tareas de limpieza y procesos de agregación de datos con un calendario fiable. Practicas Supabase Backend as a Service con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Supabase Backend as a Service?

No se requiere experiencia previa. Supabase Backend as a Service en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 3 de 3.

¿Cuánto tiempo toma la lección «Programación de tareas recurrentes con pg_cron»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Supabase Backend as a Service?

Sí. Cada lección de Supabase Backend as a Service incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Integración con servicios externos
  2. Colas de tareas con Supabase y Workers
  3. Programación de tareas recurrentes con pg_cron
← Volver a Supabase Backend as a Service