|
| 1 | +-- Setup Ensure Workers Cron |
| 2 | +-- Sets up cron jobs for worker management: ensure_workers (configurable interval) and cleanup_logs (hourly) |
| 3 | + |
| 4 | +drop function if exists pgflow.setup_ensure_workers_cron(text); |
| 5 | + |
| 6 | +create or replace function pgflow.setup_ensure_workers_cron( |
| 7 | + cron_interval text default '1 second' |
| 8 | +) |
| 9 | +returns text |
| 10 | +language plpgsql |
| 11 | +security definer |
| 12 | +set search_path = pgflow, cron, pg_temp |
| 13 | +as $$ |
| 14 | +declare |
| 15 | + ensure_workers_job_id bigint; |
| 16 | + cleanup_job_id bigint; |
| 17 | +begin |
| 18 | + -- Remove existing jobs if they exist (ignore errors if not found) |
| 19 | + begin |
| 20 | + perform cron.unschedule('pgflow_ensure_workers'); |
| 21 | + exception when others then |
| 22 | + -- Job doesn't exist, continue |
| 23 | + end; |
| 24 | + |
| 25 | + begin |
| 26 | + perform cron.unschedule('pgflow_cleanup_logs'); |
| 27 | + exception when others then |
| 28 | + -- Job doesn't exist, continue |
| 29 | + end; |
| 30 | + |
| 31 | + -- Schedule ensure_workers job with the specified interval |
| 32 | + ensure_workers_job_id := cron.schedule( |
| 33 | + job_name => 'pgflow_ensure_workers', |
| 34 | + schedule => setup_ensure_workers_cron.cron_interval, |
| 35 | + command => 'select pgflow.ensure_workers()' |
| 36 | + ); |
| 37 | + |
| 38 | + -- Schedule cleanup job to run hourly |
| 39 | + cleanup_job_id := cron.schedule( |
| 40 | + job_name => 'pgflow_cleanup_logs', |
| 41 | + schedule => '0 * * * *', |
| 42 | + command => 'select pgflow.cleanup_ensure_workers_logs()' |
| 43 | + ); |
| 44 | + |
| 45 | + return format( |
| 46 | + 'Scheduled pgflow_ensure_workers (every %s, job_id=%s) and pgflow_cleanup_logs (hourly, job_id=%s)', |
| 47 | + setup_ensure_workers_cron.cron_interval, |
| 48 | + ensure_workers_job_id, |
| 49 | + cleanup_job_id |
| 50 | + ); |
| 51 | +end; |
| 52 | +$$; |
| 53 | + |
| 54 | +comment on function pgflow.setup_ensure_workers_cron(text) is |
| 55 | +'Sets up cron jobs for worker management. |
| 56 | +Schedules pgflow_ensure_workers at the specified cron_interval (default: 1 second) to keep workers running. |
| 57 | +Schedules pgflow_cleanup_logs hourly to clean up old cron job logs. |
| 58 | +Replaces existing jobs if they exist (idempotent). |
| 59 | +Returns a confirmation message with job IDs.'; |
0 commit comments