rent
PostgreSQL extensions

pg_cron schedules

What it is

pg_cron is a cron-based job scheduler that runs inside PostgreSQL. Jobs are stored in database tables and execute SQL commands on familiar cron schedules.

What it provides

  • Recurring SQL jobs using cron syntax or intervals
  • Job metadata that can be inspected and managed with SQL
  • Database-local scheduling without a separate scheduler process

Use it for refreshing materialized views, removing expired sessions, rolling up analytics, maintaining partitions, or invoking a stored procedure on a schedule.

Use it with Rent

extension pg_cron {
  name = "pg_cron"
}

The RSL declaration makes installation and migration intent part of the reviewed application schema. Register the typed pack at runtime to call its APIs:

use rent_ext_pg_cron::{CronSchedule, PgCron, PgCronClientExt};

let pack = extensions.register_pack::<PgCron>()?;
let cron = pack.client(&pool);
let hourly = CronSchedule::new("0 * * * *")?;
let job_id = cron
    .schedule_job(
        "refresh-search",
        &hourly,
        "SELECT refresh_search()",
    )
    .await?;

let removed = cron.unschedule_job("refresh-search").await?;

CronSchedule::new rejects empty values and embedded NUL characters. PostgreSQL validates the schedule grammar when the job is submitted. A malformed schedule returns an error; unschedule_job returns false when no job with that name belongs to the current user.

Scheduling participates in your transaction. Register the pack against a transaction to publish a job only when the surrounding work commits:

let tx = client.tx().await?;
let job_id = pack
    .client(&tx.client())
    .schedule_job(
        "refresh-post-counts",
        &hourly,
        "SELECT refresh_post_counts()",
    )
    .await?;

tx.commit().await?;

Rolling back also rolls back the new job. The job itself runs later in a separate database session, not in the transaction that scheduled it. Treat its SQL command as trusted application code, never user input.

Run the application

cargo run -p rent --example extension_02_pg_cron

Set DATABASE_URL to a disposable PostgreSQL database with pg_cron installed and preloaded. Its name must match cron.database_name. Configure worker execution or the connection authentication required by pg_cron; the repository's extension profile uses background workers.

The application creates a uniquely named post-counter table, schedules an update every second, waits for the counter to increase, and removes the job. It also proves that rollback discards a scheduled job, invalid schedules fail, and removing an already removed job returns false. It cleans up its job and table. Its standalone extension declaration is crates/rent/examples/extension_02_pg_cron/schema.rsl.

On this page