0Pricing
Supabase Backend as a Service · Aula

Agendamento de Tarefas Recorrentes com pg_cron

Automatize trabalhos recorrentes dentro do Supabase usando pg_cron para agendar chamadas periódicas de Edge Functions, tarefas de limpeza e agregação de dados em um cronograma confiável.

Agendamento de Tarefas Recorrentes com pg_cron é uma aula grátis de Supabase Backend as a Service no CoddyKit. Esta é a aula 3 de 3. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Supabase Backend as a Service, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Supabase Backend as a Service inclui 3 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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

Perguntas Frequentes

A aula “Agendamento de Tarefas Recorrentes com pg_cron” é grátis?

Sim — o texto completo de “Agendamento de Tarefas Recorrentes com pg_cron” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Supabase Backend as a Service, atualize para CoddyKit PRO. O curso de Supabase Backend as a Service inclui 3 aulas no total.

O que vou aprender em “Agendamento de Tarefas Recorrentes com pg_cron”?

Automatize trabalhos recorrentes dentro do Supabase usando pg_cron para agendar chamadas periódicas de Edge Functions, tarefas de limpeza e agregação de dados em um cronograma confiável. Você pratica Supabase Backend as a Service com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Supabase Backend as a Service?

Nenhuma experiência prévia é necessária. Supabase Backend as a Service no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 3.

Quanto tempo leva a aula “Agendamento de Tarefas Recorrentes com pg_cron”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Supabase Backend as a Service?

Sim. Cada aula de Supabase Backend as a Service inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Integração com serviços externos
  2. Filas de tarefas com Supabase e workers
  3. Agendamento de Tarefas Recorrentes com pg_cron
← Voltar para Supabase Backend as a Service