Pg cron scheduled maintenance

From CarlosCaPe/octorato · View interactive version

Pg cron scheduled maintenance is an AI agent skill from the GitHub repository CarlosCaPe/octorato. pg_cron Scheduled Maintenance

How to use this skill

Skill file

pg_cron Scheduled Maintenance

What

Using PostgreSQL's pg_cron extension to schedule recurring database maintenance

jobs -- data purges, retention enforcement, statistics refresh -- directly inside

the database engine, without external schedulers.

Why

External schedulers (cron, Azure Automation, Task Scheduler) add moving parts:

credentials, network access, deployment pipelines. pg_cron runs inside PostgreSQL

itself -- no network hops, no external auth, no separate deployment. The job

definition lives alongside the data it maintains.

How

Step 1: Enable the extension

CREATE EXTENSION IF NOT EXISTS pg_cron;

Step 2: Create the maintenance procedure

CREATE OR REPLACE PROCEDURE maintenance.purge_expired_tokens()
LANGUAGE plpgsql AS $$
DECLARE
    v_deleted bigint;
BEGIN
    DELETE FROM public."RefreshTokens"
    WHERE "ExpiresAt" < now() - interval '7 days';

    GET DIAGNOSTICS v_deleted = ROW_COUNT;
    RAISE NOTICE 'Purged % expired tokens', v_deleted;
END;
$$;

Step 3: Schedule the job

-- Run every hour at minute 0
SELECT cron.schedule(
    'purge-expired-tokens',     -- job name
    '0 * * * *',                -- cron expression
    $$CALL maintenance.purge_expired_tokens()$$
);

Step 4: Validate

-- Check job is registered
SELECT jobid, jobname, schedule, command
FROM cron.job
WHERE jobname = 'purge-expired-tokens';

-- Check execution history
SELECT jobid, start_time, end_time, status, return_message
FROM cron.job_run_details
ORDER BY start_time DESC
LIMIT 10;

Step 5: Rollback plan

SELECT cron.unschedule('purge-expired-tokens');
DROP PROCEDURE IF EXISTS maintenance.purge_expired_tokens();

When to Use

Where We Used It

Related Skills

References

-- see Backlog #13 (Log rotation mechanism)

Gotchas

cron.schedule_in_database() for other databases on Azure Flexible Server

security context (SECURITY DEFINER if needed)

(set via Portal > Server parameters)


Category: Tooling | Origin: ,

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.