DuckDB Extension
Cronjob
Schedule SQL inside a running DuckDB process with cron expressions. List jobs, inspect their state, and cancel them from SQL.
On this page
Cronjob's scheduler needs background threads, which this site's browser runtime does not support. Run these examples in native DuckDB or Haybarn.
Schedule SQL inside a running DuckDB process
Cronjob runs SQL repeatedly according to a cron expression. A scheduled statement can refresh a summary table, export results, or perform another task in a DuckDB process that is already running.
The schedule belongs to that process and lives in memory. Closing DuckDB removes the jobs, so this fits a persistent application or service. For a CLI command that should start on a schedule, use an external scheduler to launch DuckDB.
Example
Create, inspect, and cancel a job
Schedule a harmless query, list the job, and remove it. This example finishes before waiting for the next scheduled run.
Tested with DuckDB 1.5.6. Run this example in the DuckDB CLI or a native client.
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://duckdb-extensions.query.farm';
INSTALL cronjob FROM query_farm;
LOAD cronjob FROM query_farm;
SET VARIABLE qf_job = (
SELECT cron('SELECT 42', '0 * * * * *')
);
SELECT * FROM cron_jobs()
WHERE job_id = getvariable('qf_job');
SELECT cron_delete(getvariable('qf_job')) AS removed;
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://haybarn-extensions.query.farm';
INSTALL cronjob FROM query_farm;
LOAD cronjob FROM query_farm;
SET VARIABLE qf_job = (
SELECT cron('SELECT 42', '0 * * * * *')
);
SELECT * FROM cron_jobs()
WHERE job_id = getvariable('qf_job');
SELECT cron_delete(getvariable('qf_job')) AS removed;
INSTALL cronjob FROM community;
LOAD cronjob;
SET VARIABLE qf_job = (
SELECT cron('SELECT 42', '0 * * * * *')
);
SELECT * FROM cron_jobs()
WHERE job_id = getvariable('qf_job');
SELECT cron_delete(getvariable('qf_job')) AS removed;
Jobs run only while the DuckDB process stays alive. The final statement cancels this example job; omit it only when you want the schedule to remain active.
Common tasks
Deep Dive
Technical Details
What you can do with one query
The shortest path from βI want this SQL to run every 5 minutesβ to a live schedule:
SELECT cron( 'CREATE OR REPLACE TABLE hourly_rollup AS SELECT bucket, SUM(amount) AS total FROM events WHERE ts >= now() - INTERVAL 1 HOUR GROUP BY bucket', '0 */5 * * * *');-- β 'task_0'cron registers the query against a six-field cron expression and returns a job_id. A background thread owned by the database wakes when the job is due, runs the query, and writes the outcome into cron_jobs. No external scheduler, no shell wrapper.
Cronjob lives entirely inside the running DuckDB process. A graceful shutdown, a kill, a crash, an OOM, a deploy β any of these wipe every registered job. There is no on-disk registry, no WAL entry, no resume after restart.
If the work needs to happen on wall-clock time regardless of process state, drive it from an external scheduler β system cron(8), systemd timers, or Kubernetes CronJob β and have it invoke DuckDB. Use this extension when DuckDB is already a long-running service and you want SQL-defined scheduling inside that lifetime.
Cron expression format
Cronjob uses six fields, with seconds as the leading field β one more than POSIX cron(8):
βββββββββββ second (0β59)β βββββββββ minute (0β59)β β βββββββ hour (0β23)β β β βββββ day of month (1β31)β β β β βββ month (1β12)β β β β β β day of week (0β6, Sun..Sat, or MONβSUN)* * * * * *Schedules are evaluated in UTC. Operators: * (any), ? (no specific value, used in day-of-month / day-of-week), , (list), - (range), / (step). crontab.guru is the standard sanity-check tool β note that crontab.guru parses the five-field POSIX form, so prepend a 0 (or */N ) to translate.
A few common patterns:
| Pattern | Meaning |
|---|---|
0 0 * * * * |
Top of every hour |
0 */5 * * * * |
Every 5 minutes |
*/15 * * * * * |
Every 15 seconds |
0 0 0 * * * |
Daily at midnight |
0 0 7 ? * MON-FRI |
Weekdays at 07:00 |
0 0 0 1 * ? |
First of every month |
What runs, where
Each run of a job opens a fresh connection to the same database the extension was loaded into. That has two consequences:
- The scheduled query sees the same tables, attached databases, persistent secrets and database-wide settings (such as
enable_external_access) as the registering session. Session state βSETvariables, temporary tables, temporary secrets β does not carry over. - Each database instance has its own scheduler. Closing the database stops its scheduler and drops its jobs, even before process exit β so if you load Cronjob in a session that targets an in-memory database, the schedule disappears with the database.
cron_jobslists only the jobs registered in that database instance (attached databases share it).
Each database has one scheduler thread, and it runs due jobs one after another. A job never overlaps itself; fire times missed while a run was in progress are skipped rather than replayed. A slow job also delays the other jobs in the same database until it finishes.
Inspect and cancel
cron_jobs is the introspection table β every registered job, its next scheduled run, the last run, and the last result (or error message):
SELECT job_id, schedule, next_run, status, last_run, last_resultFROM cron_jobs()ORDER BY next_run;cron_delete un-registers a job by job_id. It returns TRUE, or raises an error if no job has that id; a run already in progress finishes. Restart wipes everything anyway, so this is for un-registration during a live process:
SET VARIABLE job = (SELECT cron('ANALYZE', '0 30 1 * * *'));SELECT cron_delete(getvariable('job'));Changes in the DuckDB 2.0 build
The DuckDB 2.0 build reworked the scheduler. The Haybarn 1.5 build keeps the earlier behaviour.
- Timestamps are
TIMESTAMPTZ.cron_jobs().next_runandlast_runused to beVARCHARtext in the serverβs local time; they are nowTIMESTAMPTZvalues.last_runis the start of the last run. New columnsrun_count,error_countandcreated_atfollow the existing ones. - Run history.
cron_job_historylists the last 100 runs of each job with start and finish times, success and the result or error message. - Every row schedules its own job.
cronandcron_deleteareVOLATILE.SELECT cron(query, schedule) FROM tuses each rowβs query and schedule, andEXPLAINorPREPAREnever schedule a job. ANULLargument returnsNULLand schedules nothing. - Bad input is rejected up front. A query with a syntax error, an empty query, or a schedule that never matches a real date (
'0 0 0 30 2 *') is an error fromcron, instead of a job that fails on every run or runs continuously. - Jobs can inspect jobs. A scheduled query may call
cron_jobs(),cron()orcron_delete()itself, and a slow job no longer blockscron_jobs()from other sessions.
A scheduled query runs with the same rights as any other connection to the database, in the background, until it is deleted or the database closes. Only schedule SQL you would run yourself, and check cron_jobs() when you share a long-running database with others.
Pairing with other extensions
Cronjob is one of two βoperate your DuckDB processβ extensions in this collection β pick by what you want to drive:
- Cronjob schedules SQL queries on a wall-clock cadence inside the process.
- Events streams query / transaction / connection events out of the process to an external handler.
Together they cover push (Events fires on internal activity) and pull (Cronjob fires on time). Both share the same fundamental scope: they only operate while the DuckDB process is alive.
For the alerting and exporting recipes, Cronjob composes naturally with:
http_clientβ schedule a query that POSTs to a webhook (Slack, PagerDuty, generic HTTP).webmacroβ wrap repeated HTTP integrations as named macros, then schedule the macro.httpfsβ schedule aCOPY ... TOthat writes Parquet to S3 / GCS.
When to use system cron instead
If any of the following are true, reach for system cron(8) / systemd timers / Kubernetes CronJob and have that invoke duckdb -c '...':
- The DuckDB process is short-lived (a CLI invocation, a script, a query runner).
- The schedule must survive deploys, restarts, or host moves.
- You need delivery guarantees, retries, or observability the host scheduler already provides.
- The work spans multiple databases or extends beyond what one DuckDB session can express.
Cronjob is for the opposite case: DuckDB is already a long-running service, and the convenience of βschedule it from SQLβ outweighs the cost of βschedule lifetime equals process lifetime.β
Reference
Extension Contents
Quick reference to all available functions and settings organized by category.
| Name | Type | Description |
|---|---|---|
|
Scheduling
Register, list, and cancel cron-style scheduled SQL queries. Six-field cron expressions with second-level resolution. Schedules live in memory inside the DuckDB process β when the process exits, every job is forgotten. For restart-safe scheduling, drive the DuckDB run from an external orchestrator (system |
||
| cron() | Object type: Scalar function |
Register a SQL query to run on a six-field cron expression (second minute hour day-of-month month day-of-week, evaluated in UTC).
|
| cron_delete() | Object type: Scalar function |
Cancel a scheduled job by job_id (the value returned from cron or visible in cron_jobs).
|
| cron_job_history() | Object type: Table function |
DuckDB 2.0 build only. Table function listing the most recent runs of every scheduled job β up to 100 per job β with job_id, started_at and finished_at (TIMESTAMPTZ), success (BOOLEAN) and result (Success or Error: <message>).
|
| cron_jobs() | Object type: Table function |
Table function listing every scheduled job in this database β job_id, query, schedule, next_run, status (Active/Inactive), last_run, and last_result (Success or Error: <message>).
|
No extension contents match that search.
API Reference
Function Reference
Practical Examples
Cookbook
Real-world recipes and patterns for common use cases.
Schedule a query
-- Refresh an hourly rollup every 5 minutesSELECT cron( 'CREATE OR REPLACE TABLE hourly_rollup AS SELECT bucket, SUM(amount) AS total FROM events WHERE ts >= now() - INTERVAL 1 HOUR GROUP BY bucket', '0 */5 * * * *');-- β 'task_0'cron returns a job_id (e.g. task_0) β capture it if you need to cancel later. Schedules tick only while this DuckDB process is running.
Inspect whatβs scheduled
-- All scheduled jobs and their last resultSELECT job_id, schedule, next_run, status, last_run, last_resultFROM cron_jobs()ORDER BY next_run;-- Jobs that have never run yetSELECT job_id, scheduleFROM cron_jobs()WHERE last_run IS NULL;-- Jobs whose last run failedSELECT job_id, last_run, last_resultFROM cron_jobs()WHERE last_result LIKE 'Error:%';On DuckDB 2.0, next_run and last_run are TIMESTAMPTZ, so you can do date arithmetic on them directly. The Haybarn 1.5 build returns them as text.
Run history (DuckDB 2.0)
cron_job_history keeps the last 100 runs of each job:
-- Every failed run, newest firstSELECT job_id, started_at, resultFROM cron_job_history()WHERE NOT successORDER BY started_at DESC;-- Success rate per jobSELECT job_id, run_count, error_count, round(100.0 * (run_count - error_count) / nullif(run_count, 0), 1) AS success_pctFROM cron_jobs();Cancel a job
-- Keep the id cron() returns, then pass it to cron_deleteSET VARIABLE job = (SELECT cron('ANALYZE', '0 30 1 * * *'));SELECT cron_delete(getvariable('job'));-- TRUE; raises an error if no job has that id-- Cancel every job in this databaseSELECT cron_delete(job_id) FROM cron_jobs();Restart of the DuckDB process also cancels every registered job β cron_delete is for un-registering during a live process.
Periodic refresh of materialized data
-- Every 5 minutes: rebuild a recent-events rollupSELECT cron( 'CREATE OR REPLACE TABLE recent_events AS SELECT * FROM events WHERE ts >= now() - INTERVAL 1 HOUR', '0 */5 * * * *');-- Daily at 02:00: rebuild a heavy daily aggregateSELECT cron( 'CREATE OR REPLACE TABLE daily_summary AS SELECT date_trunc(''day'', ts) AS day, user_id, SUM(amount) AS total FROM events GROUP BY 1, 2', '0 0 2 * * *');Recurring exports to disk or S3
With the httpfs extension loaded, COPY ... TO writes to S3 / GCS just like any local path:
COPY ... TO takes a literal path, so each run appends a new Hive partition (export_hour=β¦/, export_date=β¦/) instead of building a file name with ||. On DuckDB 2.0, cron rejects a query with a syntax error when you schedule it.
-- Local Parquet snapshot every hourSELECT cron( 'COPY (SELECT *, strftime(now(), ''%Y%m%d_%H'') AS export_hour FROM events WHERE ts >= now() - INTERVAL 1 HOUR) TO ''/var/exports/events'' (FORMAT PARQUET, PARTITION_BY (export_hour), APPEND)', '0 0 * * * *');-- Daily export to S3 at 03:00SELECT cron( 'COPY (SELECT *, current_date AS export_date FROM daily_summary) TO ''s3://my-bucket/exports/daily'' (FORMAT PARQUET, PARTITION_BY (export_date), APPEND)', '0 0 3 * * *');Periodic Slack / webhook alerts
Pair with the http_client extension to fire a webhook when a metric crosses a threshold:
-- Every minute: post to Slack if error rate is highSELECT cron( 'WITH r AS ( SELECT 100.0 * SUM(CASE WHEN status >= 500 THEN 1 END) / COUNT(*) AS pct FROM requests WHERE ts >= now() - INTERVAL 5 MINUTE ) SELECT http_post( ''https://hooks.slack.com/services/XXX/YYY/ZZZ'', ''{"text":"Error rate '' || round(pct, 2) || ''%"}'', MAP {''Content-Type'': ''application/json''} ) FROM r WHERE pct > 5', '0 * * * * *');The query writes nothing to disk β http_post is a side effect that fires only when the WHERE filter passes.
Maintenance: ANALYZE and pruning
-- Nightly ANALYZE at 01:30SELECT cron('ANALYZE', '0 30 1 * * *');-- Prune log rows older than 30 days, weekly on Sunday at 04:00SELECT cron( 'DELETE FROM audit_log WHERE ts < now() - INTERVAL 30 DAY', '0 0 4 ? * SUN');Six-field cron quick reference
βββββββββββ second (0β59)β βββββββββ minute (0β59)β β βββββββ hour (0β23)β β β βββββ day of month (1β31)β β β β βββ month (1β12)β β β β β β day of week (0β6, Sun..Sat, or MONβSUN)* * * * * *| Pattern | Meaning |
|---|---|
0 0 * * * * |
Top of every hour |
0 */5 * * * * |
Every 5 minutes |
*/15 * * * * * |
Every 15 seconds |
0 0 0 * * * |
Daily at midnight |
0 0 7 ? * MON-FRI |
Weekdays at 07:00 |
0 0 0 1 * ? |
First of every month |
Times are evaluated in UTC: 0 0 7 ? * MON-FRI fires at 07:00 UTC. Operators: * (any), ? (no specific value), , (list), - (range), / (step). Sanity-check on crontab.guru β note crontab.guru is five-field POSIX, so drop the leading seconds field when pasting.
Restart-safe scheduling: external orchestrator
When jobs must survive process restarts, drive DuckDB from system cron(8) instead of using this extension. Example crontab entry:
*/5 * * * * /usr/local/bin/duckdb /var/data/analytics.db -c "CREATE OR REPLACE TABLE hourly_rollup AS SELECT ..."Or a systemd timer, or a Kubernetes CronJob. Use the Cronjob extension only when DuckDB is already a long-running service and the scheduleβs lifetime can equal the processβs.
Platform Support
Compatibility
Extension availability may vary by platform and DuckDB version. Check below to ensure this extension supports your environment before installation.
Quick Facts
Platforms
DuckDB 2.0.0
- Linux x86_64aarch64
- Linux (musl) Not available
- macOS Apple Silicon
- Windows x86_64x86_64 (MinGW)
- WASM Not available
Compiled binary sizes
| Platform | Architecture | Size |
|---|---|---|
| Linux | x86_64 | 14.91 MB |
| Linux | aarch64 | 12.60 MB |
| macOS | Apple Silicon | 11.24 MB |
| Windows | x86_64 | 10.20 MB |
| Windows | x86_64 (MinGW) | 17.81 MB |
Compressed download sizes for the release shown above.
DuckDB & Haybarn
Release calendar- DuckDB v2.0.0 Query.Farm repository Supported
- Haybarn v1.5.6 Built-in community repository Supported
Browser examples use Haybarn-Wasm 2.0.0-rc12.
Checked .