0Pricing
Supabase Backend as a Service · 课时

使用 pg_cron 调度周期性任务

在 Supabase 中使用 pg_cron 自动执行周期性工作,按可靠的时间计划调用 Edge Function、运行清理任务并聚合数据。

使用 pg_cron 调度周期性任务 是 CoddyKit 上的免费 Supabase Backend as a Service 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Supabase Backend as a Service 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Supabase Backend as a Service 课程共包含 3 节课。

本课时的部分内容尚未翻译,以英文显示。

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

常见问题解答

「使用 pg_cron 调度周期性任务」课时是免费的吗?

是的 — 「使用 pg_cron 调度周期性任务」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Supabase Backend as a Service 课程的其余内容,请升级到 CoddyKit PRO。 Supabase Backend as a Service 课程共包含 3 节课。

「使用 pg_cron 调度周期性任务」这节课中我会学到什么?

在 Supabase 中使用 pg_cron 自动执行周期性工作,按可靠的时间计划调用 Edge Function、运行清理任务并聚合数据。 你通过在浏览器中直接运行的动手代码来练习 Supabase Backend as a Service,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Supabase Backend as a Service 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Supabase Backend as a Service 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。

「使用 pg_cron 调度周期性任务」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Supabase Backend as a Service 课中编写并运行代码吗?

能。每节 Supabase Backend as a Service 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 集成外部服务
  2. 使用 Supabase 和工作进程构建任务队列
  3. 使用 pg_cron 调度周期性任务
← 返回 Supabase Backend as a Service