J.3. pg_timetable#

J.3. pg_timetable

J.3. pg_timetable #

J.3.1. Overview #

Version: 7.1.0

Download from nexus-public

pg_timetable is an advanced job scheduler for Tantor SE-1C, offering many advantages over traditional schedulers such as cron and others. It is completely database driven and provides a couple of advanced concepts.

J.3.2. Installation #

To install pg_timetable, download the installation script db_extension_installer.sh and make it executable:

wget https://public.tantorlabs.ru/db_extension_installer.sh && \
chmod +x db_extension_installer.sh

Next, you can install pg_timetable:

J.3.2.1. Locally from the downloaded package #

  1. Download the pg_timetable package suitable for your OS from nexus-public.

  2. Run the pg_timetable installation using db_extension_installer.sh from the downloaded package:

    ./db_extension_installer.sh \
      --from-file=<path to pg_timetable package>
    

J.3.2.2. Automatically from the package repository #

  1. Set the value of the environment variable NEXUS_URL:

    export NEXUS_URL="nexus-public.tantorlabs.ru"
    
  2. Run the pg_timetable installation using db_extension_installer.sh with the following parameters:

    ./db_extension_installer.sh \
      --database-type=tantor \
      --edition=all \
      --extension=pg_timetable
    

J.3.3. Main features #

  • Tasks can be arranged in chains

  • A chain can consist of built-int commands, SQL and executables

  • Parameters can be passed to chains

  • Missed tasks (possibly due to downtime) can be retried automatically

  • Support for configurable repetitions

  • Built-in tasks such as sending emails, etc.

  • Fully database driven configuration

  • Full support for database driven logging

  • Cron-style scheduling at the Tantor SE-1C server time zone

  • Optional concurrency protection

  • Chains and individual tasks can be enabled or disabled without deleting them

  • YAML-based chain definitions for file-based configuration

  • Task and chain can have execution timeout settings

  • OpenTelemetry tracing and metrics export (opt-in)

J.3.4. Tutorials #

J.3.4.1. Your First Scheduled Chain #

In this tutorial we'll install pg_timetable, schedule a one-off job, and watch it run.

  1. Download pg_timetable executable.

  2. Make sure your Tantor SE-1C server is up and running and has a role with CREATE privilege for a target database, e.g.

    CREATE ROLE scheduler PASSWORD 'somestrong';
    GRANT CREATE ON DATABASE my_database TO scheduler;
    
  3. Create a new job, e.g. run VACUUM each night at 00:30 Postgres server time zone

    SELECT timetable.add_job('frequent-vacuum', '30 0 * * *', 'VACUUM');
    
    add_job
    ---------
          3
    (1 row)
    
  4. Run the pg_timetable

    pg_timetable postgresql://scheduler:somestrong@localhost/my_database --clientname=vacuumer
    
  5. PROFIT!

J.3.4.2. Your First YAML Chain #

In this tutorial we'll write a chain in a YAML file, load it, and watch pg_timetable run it on startup.

  1. Make sure pg_timetable is installed and you have a role with CREATE privilege on a target database — see the first tutorial if you haven't done that yet.

  2. Create a file named hello.yaml:

    chains:
      - name: "hello-yaml"
        schedule: "@reboot"
        live: true
    
        tasks:
          - name: "hello"
            kind: "BUILTIN"
            command: "Log"
            parameters:
              - "Hello from my first YAML chain!"
    
  3. Validate the file before loading it:

    pg_timetable --file hello.yaml --validate postgresql://scheduler:somestrong@localhost/my_database
    

    You'll see:

    YAML file validation successful
    
  4. Load the chain and let pg_timetable run it. @reboot chains execute as soon as the scheduler starts, so you'll see the result immediately:

    pg_timetable --file hello.yaml --clientname=yamltester postgresql://scheduler:somestrong@localhost/my_database
    
  5. In a second terminal, check what the chain produced:

    SELECT output FROM timetable.execution_log
    WHERE chain_id = (SELECT chain_id FROM timetable.chain WHERE chain_name = 'hello-yaml');
    
                    output
    ------------------------------------------
     Logged: Hello from my first YAML chain!
    (1 row)
    
  6. PROFIT!

For the full field list, task kinds, and error-handling options, see the YAML Chain Configuration Guide and the YAML Chain Schema reference.

J.3.4.3. Handling Chain Errors #

In this tutorial we'll schedule a chain that always fails, attach an error handler that logs the failure and schedules a retry with a growing delay, and watch it back off over several attempts.

  1. Make sure you completed Your First Scheduled Chain — we'll reuse the same scheduler role and my_database.

  2. Create the retry handler. It counts how many times flaky-job has failed recently and reschedules it after a delay that doubles on every attempt:

    CREATE OR REPLACE FUNCTION retry_with_backoff() RETURNS void
    LANGUAGE plpgsql AS $$
    DECLARE
        attempts integer;
        delay interval;
    BEGIN
        SELECT count(*) INTO attempts
        FROM timetable.execution_log
        WHERE chain_id = current_setting('pg_timetable.current_chain_id')::bigint
          AND returncode != 0
          AND finished > now() - interval '10 minutes';
    
        IF attempts >= 3 THEN
            RAISE NOTICE 'Giving up after % attempts', attempts;
            RETURN;
        END IF;
    
        delay := interval '5 seconds' * (2 ^ attempts);
        RAISE NOTICE 'Attempt % failed, retrying in %', attempts, delay;
        PERFORM timetable.notify_chain_start(
            chain_id => current_setting('pg_timetable.current_chain_id')::bigint,
            worker_name => 'errortester',
            start_delay => delay);
    END
    $$;
    
  3. Schedule a chain that fails every time, wired to the handler with job_on_error:

    SELECT timetable.add_job(
        job_name          => 'flaky-job',
        job_schedule      => '@every 1 hour',
        job_command       => 'SELECT 1/0',
        job_ignore_errors => FALSE,
        job_on_error      => 'SELECT retry_with_backoff()');
    
     add_job
    ---------
           4
    (1 row)
    

    @every 1 hour schedules the first run immediately and every hour after — the handler's own retries are what make it run again sooner than that.

  4. Run pg_timetable:

    pg_timetable postgresql://scheduler:somestrong@localhost/my_database --clientname=errortester
    

    You'll see the task fail, then the handler's RAISE NOTICE messages logged roughly 5, 10, and 20 seconds apart, followed by a "Giving up" message on the fourth attempt:

    2024-01-01 12:00:00.000 [ERROR] [task:1] [error:division by zero] Task execution failed
    2024-01-01 12:00:00.010 [INFO ] [notice:Attempt 0 failed, retrying in 00:00:05] [severity:NOTICE] Notice received
    2024-01-01 12:00:05.020 [INFO ] [notice:Attempt 1 failed, retrying in 00:00:10] [severity:NOTICE] Notice received
    2024-01-01 12:00:15.030 [INFO ] [notice:Attempt 2 failed, retrying in 00:00:20] [severity:NOTICE] Notice received
    2024-01-01 12:00:35.040 [INFO ] [notice:Giving up after 3 attempts] [severity:NOTICE] Notice received
    
  5. In a second terminal, confirm every attempt was recorded:

    SELECT returncode, output FROM timetable.execution_log
    WHERE chain_id = (SELECT chain_id FROM timetable.chain WHERE chain_name = 'flaky-job')
    ORDER BY last_run;
    
     returncode |          output
    ------------+---------------------------
             -1 | division by zero
             -1 | division by zero
             -1 | division by zero
             -1 | division by zero
    (4 rows)
    
  6. PROFIT! You've handled a failing chain without babysitting it.

For every task- and chain-level error-handling field (ignore_error, on_error, autonomous), see the Commands, Tasks, and Chains Reference. For a ready-to-run version of this pattern with configurable limits, see samples/DelayedRetry.sql in Samples.

J.3.4.4. Starting and Stopping Chains Manually #

In this tutorial we'll run pg_timetable in debug mode — where all automatic scheduling is disabled and chains only fire when you trigger them by hand. This is the workflow you'll use during development, debugging, and test runs.

  1. Make sure you completed Your First Scheduled Chain — we'll reuse the same scheduler role and my_database.

  2. Create a chain that sleeps for 30 seconds. This gives us time to stop it mid-flight:

    SELECT timetable.add_job(
        job_name          => 'sleepy-chain',
        job_schedule      => '* * * * *',
        job_command       => 'SELECT pg_sleep(30)',
        job_live          => TRUE,
        job_ignore_errors => TRUE);
    
     add_job
    ---------
           5
    (1 row)
    

    The output is your chain ID — you'll need it below. Yours may differ; substitute it wherever you see 5 in the examples.

  3. Run pg_timetable with the --debug flag:

    pg_timetable --debug --clientname=debugger postgresql://scheduler:somestrong@localhost/my_database
    
    2024-01-01 12:00:00.000 [LOG]: Connection established...
    2024-01-01 12:00:00.010 [LOG]: Configuration schema created...
    2024-01-01 12:00:00.020 [LOG]: Accepting asynchronous chains execution requests...
    

    Notice what's missing: no "Checking for task chains", no "Number of chains to be executed". --debug skips the entire scheduling loop — cron expressions, intervals, and @reboot are all ignored. The scheduler only listens for your manual commands.

  4. Start the chain by hand:

    SELECT timetable.notify_chain_start(
        chain_id    => 5,
        worker_name => 'debugger');
    
     notify_chain_start
    --------------------
    
    (1 row)
    

    Back in the pg_timetable terminal:

    2024-01-01 12:05:00.000 [LOG]: Adding asynchronous chain to working queue: {5 START …}
    2024-01-01 12:05:00.010 [LOG]: Starting chain ID: 5; configuration ID: 5
    2024-01-01 12:05:30.020 [LOG]: Executed successfully chain ID: 5; configuration ID: 5
    

    The chain ran once and stopped — manual starts always execute a single run, regardless of what job_schedule says.

  5. Now start it again, and this time stop it mid-flight. From your SQL client, fire the chain:

    SELECT timetable.notify_chain_start(5, 'debugger');
    

    Wait a few seconds, then cancel it:

    SELECT timetable.notify_chain_stop(5, 'debugger');
    
     notify_chain_stop
    --------------------
    
    (1 row)
    

    The pg_timetable terminal shows the cancellation:

    2024-01-01 12:07:00.000 [LOG]: Adding asynchronous chain to working queue: {5 START …}
    2024-01-01 12:07:00.010 [LOG]: Starting chain ID: 5; configuration ID: 5
    2024-01-01 12:07:08.050 [LOG]: Adding asynchronous chain to working queue: {5 STOP …}
    2024-01-01 12:07:08.051 [ERROR]: Task execution failed: …; Error: read tcp …: i/o timeout
    2024-01-01 12:07:08.052 [LOG]: Executed successfully chain ID: 5; configuration ID: 5
    

    The task error is expected — you interrupted pg_sleep. The chain itself still reports success because we set job_ignore_errors => TRUE in step 2.

  6. PROFIT! You can now start and stop chains on demand.

A few things to remember:

  • --debug disables all automatic scheduling. Chains with run_at, @every, or @reboot will not fire unless you trigger them manually. This is the cleanest way to isolate a single chain during development.

  • In production, you can get the same effect for a single chain without --debug: set live = FALSE on its config, then start it manually when needed. A disabled chain still responds to notify_chain_start.

  • notify_chain_start takes a chain execution config ID — but add_job() creates one config per chain, so the numbers match until you add additional configs.

  • worker_name must match the --clientname of a running pg_timetable instance. If no client with that name is connected, the notification is silently dropped.

  • Manual starts accept an optional start_delay — see the Commands, Tasks, and Chains Reference for details.

Ready-to-run examples with longer chains and error handlers live in Samples — try samples/basic.sql and samples/DelayedRetry.sql.

J.3.4.5. Storing a Secret #

In this tutorial we'll store an encrypted password in the secret store, reference it from a task's connection string, and watch pg_timetable resolve it at execution time without ever writing the plaintext to a log.

  1. Make sure you completed Your First Scheduled Chain — we'll reuse the same scheduler role and my_database.

  2. Pick an encryption key and start pg_timetable with it:

    pg_timetable postgresql://scheduler:somestrong@localhost/my_database --clientname=secrettester --secret-key=mysecretkey123
    

    Leave it running; we'll come back to it in step 5.

  3. In a second terminal, install pgcrypto and store a secret for the secrettester client. pgcrypto must be installed by a role with CREATE on the database — it's a trusted extension, so scheduler can do it directly:

    CREATE EXTENSION IF NOT EXISTS pgcrypto;
    
    INSERT INTO timetable.secret (client_name, secret_name, value_enc)
    VALUES ('secrettester', 'my_pg_password',
            pgp_sym_encrypt('somestrong', 'mysecretkey123'));
    

    The encryption key here ('mysecretkey123') must match --secret-key from step 2.

  4. Create a chain with a task that connects to a database using ${secret:my_pg_password} in its connection string instead of a literal password:

    WITH new_chain AS (
        INSERT INTO timetable.chain (chain_name, run_at, live)
        VALUES ('remote-greeting', '@reboot', TRUE)
        RETURNING chain_id
    ), new_task AS (
        INSERT INTO timetable.task (chain_id, task_order, command, database_connection)
        SELECT chain_id, 10, 'SELECT $1',
               'host=localhost port=5432 dbname=my_database user=scheduler password=${secret:my_pg_password}'
        FROM new_chain
        RETURNING task_id
    )
    INSERT INTO timetable.parameter (task_id, order_id, value)
    SELECT task_id, 1, '["hello from remote"]'::jsonb FROM new_task;
    

    Adjust host/port if your Tantor SE-1C server isn't on the default local address — a database_connection normally points at a genuinely remote host; here it loops back to the same server so the tutorial is self-contained.

  5. Restart pg_timetable from step 2 (Ctrl+C, then run the same command again). @reboot chains run once, immediately on startup, so you'll see the task connect and succeed right away:

    [chain:2|remote-greeting] Starting chain
    [chain:2|remote-greeting] [task:2] Starting task
    [chain:2|remote-greeting] [task:2] Switching to remote task mode
    [chain:2|remote-greeting] [task:2] Remote connection established...
    [chain:2|remote-greeting] [task:2] Task executed successfully
    [chain:2|remote-greeting] Chain executed successfully
    

    The chain and task numbers depend on what else you've created in my_database — only the names and the sequence of messages matter.

  6. Confirm the task ran — and that the plaintext password never made it into the log:

    SELECT returncode, command, params FROM timetable.execution_log
    WHERE chain_id = (SELECT chain_id FROM timetable.chain WHERE chain_name = 'remote-greeting');
    
     returncode |  command  |         params
    ------------+-----------+-------------------------
              0 | SELECT $1 | ["hello from remote"]
    (1 row)
    

    params holds your task's arguments, not the connection string, so there was never anything to mask here — but the same guarantee applies if the secret reference is inside params itself, e.g. in samples/Mail.sql.

  7. PROFIT! You've resolved a secret at execution time without ever storing or logging it in plaintext.

For every secret-store table, function, and permission, see the Secret Store Reference. For the write-only design and its trust boundary, see Secret Store Security Model. For the administrative steps (granting a separate secret-admin role, using secrets from YAML-authored chains), see Use the Secret Store. For a fuller worked example with a dedicated remote-log table, see samples/RemoteDB.sql in Samples.

J.3.5. How-to Guides #

J.3.5.1. Schedule Common Jobs #

A variety of examples can be found in Samples. To migrate from a different scheduler, see Migration.

In a real world usually it's enough to use simple jobs. Under this term we understand:

  • job is a chain with only one task (step) in it;

  • it doesn't use complicated logic, but rather simple command;

  • it doesn't require complex transaction handling, since one task is implicitely executed as a single transaction.

For such a group of chains we've introduced a special function timetable.add_job().

For the full timetable.add_job() parameter reference, see Database Schema.

J.3.5.1.1. Examples #
  1. Run public.my_func() at 00:05 every day in August Postgres server time zone:

    SELECT timetable.add_job('execute-func', '5 0 * 8 *', 'SELECT public.my_func()');
    
  2. Run VACUUM at minute 23 past every 2nd hour from 0 through 20 every day Postgres server time zone:

    SELECT timetable.add_job('run-vacuum', '23 0-20/2 * * *', 'VACUUM');
    
  3. Refresh materialized view every 2 hours:

    SELECT timetable.add_job('refresh-matview', '@every 2 hours', 'REFRESH MATERIALIZED VIEW public.mat_view');
    
  4. Clear log table after pg_timetable restart:

    SELECT timetable.add_job('clear-log', '@reboot', 'TRUNCATE timetable.log');
    
  5. Reindex at midnight Postgres server time zone on Sundays with reindexdb utility:

    • using default database under default user (no command line arguments)

      SELECT timetable.add_job('reindex', '0 0 * * 7', 'reindexdb', job_kind := 'PROGRAM');
      
    • specifying target database and tables, and be verbose

      SELECT timetable.add_job('reindex', '0 0 * * 7', 'reindexdb', 
          '["--table=foo", "--dbname=postgres", "--verbose"]'::jsonb, 'PROGRAM');
      
    • passing password using environment variable through bash shell

      SELECT timetable.add_job('reindex', '0 0 * * 7', 'bash', 
          '["-c", "PGPASSWORD=5m3R7K4754p4m reindexdb -U postgres -h 192.168.0.221 -v"]'::jsonb, 
          'PROGRAM');
      
  6. Run a job at every scheduler loop tick (every 60 seconds by default) — pass NULL as the schedule:

    SELECT timetable.add_job('frequent-job', NULL, 'SELECT 1');
    

    The job is started automatically on every tick and can additionally be triggered on demand with timetable.notify_chain_start().

J.3.5.2. Samples #

J.3.5.2.1. Create a basic one-step chain with parameters #

Use a CTE to insert directly into the timetable schema tables:

DELETE FROM timetable.chain WHERE chain_name = 'notify_every_minute';

SELECT timetable.add_job(
    job_name            => 'notify_every_minute',
    job_schedule        => '* * * * *',
    job_command         => 'SELECT pg_notify($1, $2)',
    job_parameters      => '[ "TT_CHANNEL", "Ahoj from SQL base task" ]' :: jsonb,
    job_kind            => 'SQL'::timetable.command_kind,
    job_client_name     => NULL,
    job_max_instances   => 1,
    job_live            => TRUE,
    job_self_destruct   => FALSE,
    job_ignore_errors   => TRUE
) as chain_id;
J.3.5.2.2. Send an email from a chain #

Check whether there are emails to send, send them, and log the execution status. No setup is required beyond specifying parameters at chain-creation time:

DO $$
    -- An example for using the SendMail task.
DECLARE
    v_mail_task_id bigint;
    v_log_task_id bigint;
    v_chain_id bigint;
BEGIN
    -- Get the chain id
    INSERT INTO timetable.chain (chain_name, max_instances, live) VALUES ('send_mail', 1, TRUE)
    RETURNING chain_id INTO v_chain_id;

    -- Add SendMail task
    INSERT INTO timetable.task (chain_id, task_order, kind, command) 
    SELECT v_chain_id, 10, 'BUILTIN', 'SendMail'
    RETURNING task_id INTO v_mail_task_id;

    -- Create the parameters for the SensMail task
        -- "username":	      The username used for authenticating on the mail server
        -- "password":        The password used for authenticating on the mail server
        -- "serverhost":      The IP address or hostname of the mail server
        -- "serverport":      The port of the mail server
        -- "senderaddr":      The email that will appear as the sender
        -- "ccaddr":	      String array of the recipients(Cc) email addresses
        -- "bccaddr":	      String array of the recipients(Bcc) email addresses
        -- "toaddr":          String array of the recipients(To) email addresses
        -- "subject":	      Subject of the email
        -- "attachment":      String array of the attachments (local file)
        -- "attachmentdata":  Pairs of name and base64-encoded content
        -- "msgbody":	      The body of the email

    INSERT INTO timetable.parameter (task_id, order_id, value)
        VALUES (v_mail_task_id, 1, '{
                "username":     "user@example.com",
                "password":     "password",
                "serverhost":   "smtp.example.com",
                "serverport":   587,
                "senderaddr":   "user@example.com",
                "ccaddr":       ["recipient_cc@example.com"],
                "bccaddr":      ["recipient_bcc@example.com"],
                "toaddr":       ["recipient@example.com"],
                "subject":      "pg_timetable - No Reply",
                "attachment":   ["D:\\Go stuff\\Books\\Concurrency in Go.pdf","report.yaml"],
                "attachmentdata": [{"name": "File.txt", "base64data": "RmlsZSBDb250ZW50"}],
                "msgbody":      "<b>Hello User,</b> <p>I got some Go books for you enjoy</p> <i>pg_timetable</i>!",
                "contenttype":  "text/html; charset=UTF-8"
                }'::jsonb);
    
    -- Add Log task and make it the last task using `task_order` column (=30)
    INSERT INTO timetable.task (chain_id, task_order, kind, command) 
    SELECT v_chain_id, 30, 'BUILTIN', 'Log'
    RETURNING task_id INTO v_log_task_id;

    -- Add housekeeping task, that will delete sent mail and update parameter for the previous logging task
    -- Since we're using special add_task() function we don't need to specify the `chain_id`.
    -- Function will take the same `chain_id` from the parent task, SendMail in this particular case
    PERFORM timetable.add_task(
        kind => 'SQL', 
        parent_id => v_mail_task_id,
        command => format(
$query$WITH sent_mail(toaddr) AS (DELETE FROM timetable.parameter WHERE task_id = %s RETURNING value->>'username')
INSERT INTO timetable.parameter (task_id, order_id, value) 
SELECT %s, 1, to_jsonb('Sent emails to: ' || string_agg(sent_mail.toaddr, ';'))
FROM sent_mail
ON CONFLICT (task_id, order_id) DO UPDATE SET value = EXCLUDED.value$query$, 
                v_mail_task_id, v_log_task_id
            ),
        order_delta => 10
    );

-- In the end we should have something like this. Note, that even Log task was created earlier it will be executed later
-- due to `task_order` column.

-- timetable=> SELECT task_id, chain_id, kind, left(command, 50) FROM timetable.task ORDER BY task_order;  
--  task_id | chain_id | task_order |  kind   |                             left
-- ---------+----------+------------+---------+---------------------------------------------------------------
--       45 |       24 |         10 | BUILTIN | SendMail
--       47 |       24 |         20 | SQL     | WITH sent_mail(toaddr) AS (DELETE FROM timetable.p
--       46 |       24 |         30 | BUILTIN | Log
-- (3 rows)

END;
$$
LANGUAGE PLPGSQL;
J.3.5.2.3. Download, transform, and import data in one chain #

Use a DO statement to insert a three-step chain directly into the timetable schema tables:

-- Prepare the destination table 'location'
CREATE TABLE IF NOT EXISTS public.city(
    city text,
    lat numeric,
    lng numeric,
    country text,
    iso2 text,
    admin_name text,
    capital text,
    population bigint,
    population_proper bigint);
   
GRANT ALL ON public.city TO scheduler;

-- An enhanced example consisting of three tasks:
-- 1. Download text file from internet using BUILT-IN command
-- 2. Remove accents (diacritic signs) from letters using PROGRAM command (can be done with `unaccent` PostgreSQL extension) 
-- 3. Import text file as CSV file using BUILT-IN command (can be down with `psql -c /copy`)
DO $$
DECLARE
    v_task_id bigint;
    v_chain_id bigint;
BEGIN
    -- Create the chain with default values executed every minute (NULL == '* * * * *' :: timetable.cron)
    INSERT INTO timetable.chain (chain_name, live)
    VALUES ('download_locations_and_aggregate', TRUE)
    RETURNING chain_id INTO v_chain_id;

    -- Step 1. Download file from the server
    -- Create the chain
    INSERT INTO timetable.task (chain_id, task_order, kind, command, ignore_error)
    VALUES (v_chain_id, 1, 'BUILTIN', 'Download', TRUE)
    RETURNING task_id INTO v_task_id;

    -- Create the parameters for the step 1:
    INSERT INTO timetable.parameter (task_id, order_id, value)
        VALUES (v_task_id, 1, 
           '{
                "workersnum": 1,
                "fileurls": ["https://simplemaps.com/static/data/country-cities/mt/mt.csv"], 
                "destpath": "."
            }'::jsonb);
    
    RAISE NOTICE 'Step 1 completed. Chain added with ID: %; DownloadFile task added with ID: %', v_chain_id, v_task_id;

    -- Step 2. Transform Unicode characters into ASCII
    -- Create the program task to call 'uconv' and name it 'unaccent'
    INSERT INTO timetable.task (chain_id, task_order, kind, command, ignore_error, task_name)
    VALUES (v_chain_id, 2, 'PROGRAM', 'uconv', TRUE, 'remove_accents')
    RETURNING task_id INTO v_task_id;

    -- Create the parameters for the 'unaccent' task. Input and output files in this case
    -- Under Windows we should call PowerShell instead of "uconv" with command:
    -- Set-content "orte_ansi.txt" ((Get-content "orte.txt").Normalize("FormD") -replace '\p{M}', '')
    INSERT INTO timetable.parameter (task_id, order_id, value)
        VALUES (v_task_id, 1, '["-x", "Latin-ASCII", "-o", "mt_ansi.csv", "mt.csv"]'::jsonb);

    RAISE NOTICE 'Step 2 completed. Unacent task added with ID: %', v_task_id;

    -- Step 3. Import ASCII file to PostgreSQL table using "CopyFromFile" built-in command
    INSERT INTO timetable.task (chain_id, task_order, kind, command)
        VALUES (v_chain_id, 3, 'BUILTIN', 'CopyFromFile')
    RETURNING task_id INTO v_task_id;

    -- Add the parameters for the download task. Execute client side COPY to 'location' from 'orte_ansi.txt'
    INSERT INTO timetable.parameter (task_id, order_id, value)
        VALUES (v_task_id, 1, '{"sql": "COPY city FROM STDIN (FORMAT csv, HEADER true)", "filename": "mt_ansi.csv" }'::jsonb);

    RAISE NOTICE 'Step 3 completed. Import task added with ID: %', v_task_id;

    INSERT INTO timetable.task (chain_id, task_order, kind, command, ignore_error, task_name)
    VALUES (v_chain_id, 4, 'PROGRAM', 'bash', TRUE, 'remove_csv_files')
    RETURNING task_id INTO v_task_id;

    INSERT INTO timetable.parameter (task_id, order_id, value)
    VALUES (v_task_id, 1, '["-c", "rm *.csv"]'::jsonb);
   
   RAISE NOTICE 'Step 4 completed. Cleanup task added with ID: %', v_task_id;
END;
$$ LANGUAGE PLPGSQL;
J.3.5.2.4. Run a task in an autonomous transaction #

Run a task outside the chain's transaction for operations that cannot participate in one, e.g. CREATE DATABASE, REINDEX, VACUUM, CREATE TABLESPACE:

-- An advanced example showing how to use atutonomous tasks.
-- This one-task chain will execute test_proc() procedure.
-- Since procedure will make two commits (after f1() and f2())
-- we cannot use it as a regular task, because all regular tasks 
-- must be executed in the context of a single chain transaction.
-- Same rule applies for some other SQL commands, 
-- e.g. CREATE DATABASE, REINDEX, VACUUM, CREATE TABLESPACE, etc.
CREATE OR REPLACE FUNCTION f (msg TEXT) RETURNS void AS $$
BEGIN 
    RAISE notice '%', msg; 
END;
$$ LANGUAGE PLPGSQL;

CREATE OR REPLACE PROCEDURE test_proc () AS $$
BEGIN
    PERFORM f('hey 1');
    COMMIT;
    PERFORM f('hey 2');
    COMMIT;
END;
$$
LANGUAGE PLPGSQL;

DELETE FROM timetable.chain WHERE chain_name = 'call_proc_every_10s';

WITH
    cte_chain (v_chain_id) AS (
        INSERT INTO timetable.chain (chain_name, run_at, max_instances, live, self_destruct) 
        VALUES (
            'call_proc_every_10s', -- chain_name, 
            '@every 10 seconds',        -- run_at,
            1,     -- max_instances, 
            TRUE,  -- live, 
            FALSE -- self_destruct
        ) RETURNING chain_id
    ),
    cte_task(v_task_id) AS (
        INSERT INTO timetable.task (chain_id, task_order, kind, command, ignore_error, autonomous)
        SELECT v_chain_id, 10, 'SQL', 'CALL test_proc()', TRUE, TRUE
        FROM cte_chain
        RETURNING task_id
    )
SELECT v_chain_id, v_task_id FROM cte_task, cte_chain;
J.3.5.2.5. Shut down the scheduler and terminate the session #

Use the built-in shutdown task to control maintenance windows, restart the scheduler for updates, or stop the session before dropping the database:

-- This one-task chain (aka job) will terminate pg_timetable session.
-- This is useful for maintaining purposes or before database being destroyed.
-- One should take care of restarting pg_timetable if needed.

SELECT timetable.add_job (
    job_name     => 'shutdown_on_schedule',
    job_schedule => '* * 1 * *',
    job_command  => 'Shutdown',
    job_kind     => 'BUILTIN'
);
J.3.5.2.6. Access the previous task's result code and output from the next task #

Check the return code and output of a previous task — only possible when that task has ignore_error = true, otherwise the scheduler stops the chain on failure. This sample also calculates the count of failed, successful, and total tasks executed, and the resulting success ratio:

WITH 
    cte_chain (v_chain_id) AS ( -- let's create a new chain and add tasks to it later
        INSERT INTO timetable.chain (chain_name, run_at, max_instances, live) 
        VALUES ('many_tasks', '* * * * *', 1, true)
        RETURNING chain_id
    ),
    cte_tasks(v_task_id) AS ( -- now we'll add 500 tasks to the chain, some of them will fail
        INSERT INTO timetable.task (chain_id, task_order, kind, command, ignore_error)
        SELECT v_chain_id, g.s, 'SQL', 'SELECT 1.0 / round(random())::int4;', true
        FROM cte_chain, generate_series(1, 500) AS g(s)
        RETURNING task_id
    ),
    report_task(v_task_id) AS ( -- and the last reporting task will calculate the statistic
        INSERT INTO timetable.task (chain_id, task_order, kind, command)
        SELECT v_chain_id, 501, 'SQL', $CMD$DO
$$
DECLARE
    s TEXT;
BEGIN
    WITH report AS (
        SELECT 
        count(*) FILTER (WHERE returncode = 0) AS success,
        count(*) FILTER (WHERE returncode != 0) AS fail,
        count(*) AS total
        FROM timetable.execution_log 
        WHERE chain_id = current_setting('pg_timetable.current_chain_id')::bigint
          AND txid = txid_current()
    )
    SELECT 'Tasks executed:' || total || 
         '; succeeded: ' || success || 
         '; failed: ' || fail || 
         '; ratio: ' || 100.0*success/GREATEST(total,1)
    INTO s
    FROM report;
    RAISE NOTICE '%', s;
END;
$$
$CMD$
        FROM cte_chain
        RETURNING task_id
    )
SELECT v_chain_id FROM cte_chain

For the secret store, see Use the Secret Store.

J.3.5.3. Migration from others schedulers #

J.3.5.3.1. Migrate jobs from pg_cron to pg_timetable #

If you want to quickly export jobs scheduled from pg_cron to pg_timetable, you can use this SQL snippet:

SELECT timetable.add_job(
    job_name            => COALESCE(jobname, 'job: ' || command),
    job_schedule        => schedule,
    job_command         => command,
    job_kind            => 'SQL',
    job_live            => active
) FROM cron.job;

The timetable.add_job(), however, has some limitations. First of all, the function will mark the task created as autonomous, specifying scheduler should execute the task out of the chain transaction. It's not an error, but many autonomous chains may cause some extra connections to be used.

Secondly, database connection parameters are lost for source pg_cron jobs, making all jobs local. To export every information available precisely as possible, use this SQL snippet under the role they were scheduled in pg_cron:

SET ROLE 'scheduler'; -- set the role used by pg_cron

WITH cron_chain AS (
    SELECT
        nextval('timetable.chain_chain_id_seq'::regclass) AS cron_id,
        jobname,
        schedule,
        active,
        command,
        CASE WHEN 
            database != current_database()
            OR nodename != 'localhost'
            OR username != CURRENT_USER
            OR nodeport != inet_server_port() 
        THEN
            format('host=%s port=%s dbname=%s user=%s', nodename, nodeport, database, username)
        END AS connstr
    FROM
        cron.job
),
cte_chain AS (
	INSERT INTO timetable.chain (chain_id, chain_name, run_at, live)
	    SELECT 
	    	cron_id, COALESCE(jobname, 'cronjob' || cron_id), schedule, active
	    FROM
	    	cron_chain
),
cte_tasks AS (
	INSERT INTO timetable.task (chain_id, task_order, kind, command, database_connection)
	    SELECT
	    	cron_id, 1, 'SQL', command, connstr
	    FROM
	    	cron_chain
	    RETURNING
	        chain_id, task_id
)
SELECT * FROM cte_tasks;
J.3.5.3.2. Migrate jobs from pgAgent to pg_timetable #

To migrate jobs from pgAgent, please use this script. pgAgent doesn't have concept of PROGRAM task, thus to emulate BATCH steps, pg_timetable will execute them inside the shell. You may change the shell by editing cte_shell CTE clause.

CREATE OR REPLACE FUNCTION bool_array_to_cron(bool[], start_with int4 DEFAULT 0) RETURNS TEXT AS
$$
WITH u AS (
	SELECT unnest($1) e, generate_series($2, array_length($1, 1)-1+$2) AS i 
)
SELECT COALESCE(string_agg(i::text, ','), '*') FROM u WHERE e
$$
LANGUAGE sql;


WITH
cte_shell(shell, cmd_param) AS (
	VALUES ('sh', '-c') -- set the shell you want to use for batch steps, e.g. "pwsh -c", "cmd /C"
),
pga_schedule AS (
	SELECT
		s.jscjobid,
		s.jscname,
		format('%s %s %s %s %s', 
			bool_array_to_cron(s.jscminutes), 
			bool_array_to_cron(s.jschours), 
			bool_array_to_cron(s.jscmonthdays), 
			bool_array_to_cron(s.jscmonths, 1), 
			bool_array_to_cron(s.jscweekdays, 1)) AS schedule
	FROM 
		pgagent.pga_schedule s  
	WHERE s.jscenabled 
			AND now() < COALESCE(s.jscend, 'infinity'::timestamptz)
			AND now() > s.jscstart
),
pga_chain AS (
    SELECT
        nextval('timetable.chain_chain_id_seq'::regclass) AS chain_id,
        jobid,
        format('%s @ %s', jobname, jscname) AS jobname,
        jobhostagent,
        jobenabled,
        schedule
    FROM
        pgagent.pga_job JOIN pga_schedule ON jobid = jscjobid
),
cte_chain AS (
	INSERT INTO timetable.chain (chain_id, chain_name, client_name, run_at, live)
	    SELECT 
	    	chain_id, jobname, jobhostagent, schedule, jobenabled
	    FROM
	    	pga_chain
),
pga_step AS (
	SELECT 
		c.chain_id,
		nextval('timetable.task_task_id_seq'::regclass) AS task_id,
		rank() OVER (ORDER BY jstname) AS jstorder,
		jstid,
		jstname,
		jstenabled,
		CASE jstkind WHEN 'b' THEN 'PROGRAM' ELSE 'SQL' END AS jstkind,
		jstcode,
		COALESCE(
			NULLIF(jstconnstr, ''), 
			CASE 
				WHEN jstdbname = current_database() THEN NULL
				WHEN jstdbname > '' THEN 'dbname=' || jstdbname 
			END
		) AS jstconnstr,
		jstonerror != 'f' AS jstignoreerror
	FROM
		pga_chain c JOIN pgagent.pga_jobstep js ON c.jobid = js.jstjobid
),
cte_tasks AS (
	INSERT INTO timetable.task(task_id, chain_id, task_name, task_order, kind, command, database_connection)
	    SELECT
	    	task_id, chain_id, jstname, jstorder, jstkind::timetable.command_kind, 
	    	CASE jstkind WHEN 'SQL' THEN jstcode ELSE sh.shell END,
	    	jstconnstr
	    FROM
	    	pga_step, cte_shell sh
),
cte_parameters AS (
	INSERT INTO timetable.parameter (task_id, order_id, value)
		SELECT 
			task_id, 1, jsonb_build_array(sh.cmd_param, s.jstcode)
	    FROM
	    	pga_step s, cte_shell sh
	    WHERE 
	    	s.jstkind = 'PROGRAM'
)
SELECT * FROM pga_chain;

J.3.5.4. YAML Chain Configuration Guide #

This guide shows you how to define pg_timetable chains in YAML files as an alternative to SQL-based configuration.

J.3.5.4.1. Basic Usage #
# Load a single YAML file
pg_timetable --file chains.yaml postgresql://user:pass@host/db

# Load several startup files in order
pg_timetable --file bootstrap.sql --file chains/base.yaml --file chains/prod.yaml ******host/db

# Validate YAML without importing
pg_timetable --file chains.yaml --validate

# Replace existing chains with same names
pg_timetable --file chains.yaml --replace postgresql://user:pass@host/db

Each --file value is processed in the order provided, so you can mix SQL bootstrap scripts and YAML chain definitions in one startup command.

J.3.5.4.2. YAML Format #

See the YAML Chain Schema reference for the complete field list and defaults. The patterns below show common authoring tasks.

J.3.5.4.2.1. Task Parameters #

Each task can have multiple parameter entries, with each entry causing a separate execution:

# SQL task parameters (arrays of values)
- name: "sql-task"
  kind: "SQL"
  command: "SELECT $1, $2, $3, $4"
  parameters:
    - ["one", 2, 3.14, false]    # First execution
    - ["two", 4, 6.28, true]     # Second execution

# PROGRAM task parameters (arrays of command-line arguments)
- name: "program-task"
  kind: "PROGRAM"
  command: "iconv"
  parameters:
    - ["-x", "Latin-ASCII", "-o", "file1.txt", "input1.txt"]
    - ["-x", "UTF-8", "-o", "file2.txt", "input2.txt"]

BUILTIN commands (Sleep, Log, SendMail, Download, CopyFromFile, CopyToFile, CopyFromProgram, CopyToProgram) take the same parameter value in YAML as in SQL — only the surrounding syntax differs. For every command's exact JSON shape and a worked example, see Parameter value format.

J.3.5.4.2.2. Examples #

For a minimal single-task example, see YAML Chain Schema.

J.3.5.4.2.3. Multi-Step Chain #
chains:
  - name: "data-pipeline"
    schedule: "0 1 * * *"  # 1 AM daily
    live: true
    max_instances: 1
    timeout: 7200000  # 2 hours
    
    tasks:
      - name: "extract"
        command: |
          CREATE TEMP TABLE temp_data AS
          SELECT * FROM source_table 
          WHERE date >= CURRENT_DATE - INTERVAL '1 day'
          
      - name: "validate"
        command: |
          DO $$
          BEGIN
            IF (SELECT COUNT(*) FROM temp_data) = 0 THEN
              RAISE EXCEPTION 'No data to process';
            END IF;
          END $$
          
      - name: "transform"
        command: "CALL transform_data_procedure()"
        autonomous: true
        
      - name: "load"
        command: "INSERT INTO target_table SELECT * FROM temp_data"
J.3.5.4.2.4. Multiple Chains in One File #
chains:
  # Monitoring chain
  - name: "health-check"
    schedule: "*/15 * * * *"  # Every 15 minutes
    live: true
    
    tasks:
      - command: "SELECT check_database_health()"
      
  # Cleanup chain  
  - name: "hourly-cleanup"
    schedule: "0 * * * *"  # Every hour
    live: true
    
    tasks:
      - command: "DELETE FROM logs WHERE created_at < now() - interval '7 days'"
J.3.5.4.2.5. Disabling a Task Without Removing It #
chains:
  - name: "maintenance-window"
    schedule: "0 1 * * *"
    live: true

    tasks:
      - name: "pre-check"
        command: "SELECT run_precheck()"
      - name: "paused-step"
        command: "SELECT run_optional_step()"
        live: false
      - name: "post-check"
        command: "SELECT run_postcheck()"

Tasks with live: false remain part of the chain definition but are skipped until re-enabled.

J.3.5.4.3. Advanced Features #
J.3.5.4.3.1. Error Handling #

Control error behavior with ignore_error and on_error:

chains:
  - name: "resilient-chain"
    on_error: |
      SELECT pg_notify('monitoring', 
            format('{"ConfigID": %s, "Message": "Something bad happened"}', 
                current_setting('pg_timetable.current_chain_id')::bigint))
    
    tasks:
      - name: "risky-task"
        command: "SELECT might_fail()"
        ignore_error: true  # Continue chain execution even if this task fails
        
      - name: "cleanup-task"
        command: "SELECT cleanup()"  # Always runs, even if previous task failed
J.3.5.4.3.2. Transaction Control #

Use autonomous: true for tasks that need to run outside the main transaction:

tasks:
  - name: "vacuum-task"
    command: "VACUUM FULL heavy_table"
    autonomous: true  # Required for VACUUM FULL
    
  - name: "create-database"
    command: "CREATE DATABASE new_db"
    autonomous: true  # CREATE DATABASE requires autonomous transaction
J.3.5.4.3.3. Remote Databases #

Execute tasks on different databases:

tasks:
  - name: "cross-database-task"
    command: "SELECT sync_data()"
    connect_string: "postgresql://user:pass@other-host/other-db"
J.3.5.4.4. Migration from SQL #
J.3.5.4.4.1. Converting Existing Chains #

To convert SQL-based chains to YAML:

  1. Query chain and tasks information:

    SELECT *
    FROM timetable.chain c 
    WHERE c.chain_name = 'my-chain';
    
    SELECT t.*
    FROM timetable.task t JOIN 
         timetable.chain c ON t.chain_id = c.chain_id AND c.chain_name = 'my-chain'
    ORDER BY t.task_order;
    
  2. Map to YAML format:

    • chain_name → name

    • run_at → schedule

    • live → live

    • max_instances → max_instances

    • Task fields map directly

  3. Test the conversion:

    pg_timetable --file converted.yaml --validate
    
J.3.5.4.4.2. Example Migration #

Original SQL:

SELECT timetable.add_job(
    job_name => 'daily-report',
    job_schedule => '0 9 * * *',
    job_command => 'CALL generate_report()',
    job_live => TRUE
);

Converted YAML:

chains:
  - name: "daily-report"
    schedule: "0 9 * * *"
    live: true
    
    tasks:
      - command: "CALL generate_report()"
J.3.5.4.5. Troubleshooting #
J.3.5.4.5.1. Common Issues #

Invalid YAML syntax:

Error: failed to parse YAML: yaml: line 5: found character that cannot start any token

→ Check indentation and quotes

Invalid cron format:

Error: invalid cron format: 0 9 * * (expected 5 fields)

→ Ensure cron has exactly 5 fields

Chain already exists:

Error: chain 'my-chain' already exists (use --replace flag to overwrite)

→ Use --replace flag or choose different name

Missing required fields:

Error: chain 1: chain name is required

→ Check all required fields are present

J.3.5.4.6. Secrets #

YAML-authored chains do not support ${secret:name} resolution in v1 — see Use secrets with YAML-authored chains for the two supported workarounds.

J.3.5.5. Use the Secret Store #

J.3.5.5.1. Store and reference a secret #

samples/Mail.sql and samples/RemoteDB.sql demonstrate the secret store: a ${secret:name} reference in a parameter (jsonb) or a database_connection conninfo string is replaced at execution time with the decrypted value of the matching timetable.secret row for the running client.

  1. Configure --secret-key (or PGTT_SECRET_KEY) on the scheduler process.

  2. Install pgcrypto (any schema) and insert a row into timetable.secret with pgp_sym_encrypt using the same key:

    CREATE EXTENSION IF NOT EXISTS pgcrypto; -- by the DBA, not by pg_timetable
    INSERT INTO timetable.secret (client_name, secret_name, value_enc)
    VALUES ('worker-1', 'smtp_main',
            pgp_sym_encrypt('your-password', 'PGTT_SECRET_KEY_VALUE'));
    

    The cluster role must own timetable.secret for this to succeed.

  3. Replace the literal in your parameter with "${secret:your_name}" (for jsonb fields) or password=${secret:your_name} (for connection strings).

  4. Optional: grant a separate administrative role write-only access. The schema grants no default privileges on timetable.secret, so an operator who wants to delegate secret administration without revealing plaintext must GRANT INSERT, UPDATE, DELETE ON timetable.secret TO admin_role manually:

    GRANT INSERT, UPDATE, DELETE ON timetable.secret TO admin_role;
    

    resolve_secret is owned by the scheduler role and not granted to any other role by default.

J.3.5.5.2. Use secrets with YAML-authored chains #

YAML-authored chains do not support ${secret:name} references in v1. The reference syntax is a string-substitution feature implemented in the Go runtime after parameter.value is materialized into the database; the YAML loader does not perform secret resolution. A YAML chain that needs a secret must either:

  • reference a timetable.task row whose parameter.value already contains ${secret:name} (i.e., the chain was originally created via SQL using samples/Mail.sql or samples/RemoteDB.sql as a template; see the Store and reference a secret section above for the steps), or

  • use a connection-string literal in database_connection and accept the trade-off (the password is then visible to DB readers, backups, and dumps).

J.3.5.5.2.1. What you need to enable the secret store #

pgcrypto is not installed by pg_timetable. To use ${secret:name} references, the database administrator must install pgcrypto once per database (any schema; it is a trusted extension and can be installed by any role holding CREATE on the database). The scheduler is configured with --secret-key (or PGTT_SECRET_KEY) and secret rows are inserted with pgp_sym_encrypt from the same schema.

The store is opt-in syntax: chains whose parameter.value holds a literal password continue to work unchanged.

For the schema and reference syntax, see Secret Store Reference.

For the trust boundary, design rationale, and credential-handling recommendations, see Secret Store Security Model. For the schema and syntax, see Secret Store Reference.

J.3.5.6. Enable OpenTelemetry #

Note

OTel support is fully opt-in. When --otel-endpoint is not configured, pg_timetable behaves exactly as before with zero additional overhead.

J.3.5.6.1. Signals #

pg_timetable supports two OTel signals, each independently enabled:

SignalFlagWhat it provides
Traces--otel-tracesA distributed trace per chain execution with child spans for every task
Metrics--otel-metricsCounters and a histogram covering chain and task throughput
J.3.5.6.2. Quick Start #
J.3.5.6.2.2. Traces only — Jaeger #

Traces only

Jaeger implements the OTLP trace service only. Enabling --otel-metrics with a Jaeger endpoint will produce export errors. Use this setup when you need traces exclusively.

# 1. Start Jaeger
docker run --rm -d -p 4317:4317 -p 16686:16686 jaegertracing/all-in-one:latest

# 2. Run pg_timetable with tracing only
pg_timetable \
  --otel-endpoint grpc://localhost:4317 \
  --otel-traces \
  --otel-insecure \
  postgresql://scheduler:pass@localhost/mydb

Open http://localhost:16686 and select service pg_timetable to see traces.

J.3.5.6.2.3. Metrics only — OTel Collector → Prometheus #
pg_timetable \
  --otel-endpoint grpc://otel-collector:4317 \
  --otel-metrics \
  --otel-metric-period 15 \
  postgresql://scheduler:pass@localhost/mydb
J.3.5.6.3. Reduce Trace Volume #

By default, 100 % of chain executions are traced. For high-frequency deployments you can reduce trace volume with a ratio sampler:

# Trace 10 % of chain executions
pg_timetable --otel-traces --otel-sample-ratio 0.1 \
  --otel-endpoint grpc://localhost:4317 \
  postgresql://scheduler:pass@localhost/mydb

For every flag, span attribute, metric, and config key, see the OpenTelemetry Reference.

J.3.5.7. Limit Database Sessions When Running Many Jobs #

If you're scheduling many chains and need to control how many database connections pg_timetable opens, use the settings below instead of guessing.

J.3.5.7.1. Calculate the connection ceiling #

One pg_timetable instance opens at most:

max_conn = --cron-workers + --interval-workers + 3

The +3 covers the regular chain receiver, the interval chain receiver, and the database logger — each holds its own connection alongside the worker pool. With the defaults (--cron-workers=16 --interval-workers=16) that's 35 connections per instance; running several instances against the same server multiplies that ceiling by the instance count.

To limit sessions, lower --cron-workers and/or --interval-workers (see the Command-Line Reference):

pg_timetable postgresql://scheduler:somestrong@localhost/my_database --cron-workers=4 --interval-workers=2
J.3.5.7.2. Reduce concurrent chain executions without touching workers #

job_max_instances (or max_instances in YAML) caps how many copies of one specific chain run at the same time — it does nothing for chains that already run once and self-destruct, since there's only ever one instance of those in flight. To cut the number of simultaneously running chains overall, without lowering worker counts:

  • schedule chains less aggressively, e.g. every 10 minutes instead of every minute;

  • use an @after schedule instead of @every for chains whose next run should wait until the previous one finished, rather than firing on a fixed clock regardless of overlap.

For the full field list, see Table timetable.chain.

J.3.5.7.3. If you see "Failed to send chain to the execution channel" #

This means every worker was busy when the scheduler tried to hand off a newly due chain, and the in-memory queue between the scheduler and the workers was full. Since the queue is generously buffered, this indicates a sustained backlog rather than a brief spike — the fixes are the same levers as above: fewer, less frequent chains, or more workers if the database can take the extra connections.

J.3.5.7.4. Monitor before you tune #

Check timetable.log for this error and general execution health, and cross-reference pg_stat_activity against your calculated max_conn to confirm the ceiling holds in practice:

SELECT count(*) FROM pg_stat_activity WHERE application_name = 'pg_timetable';

J.3.6. References books #

J.3.6.1. REST API #

pg_timetable has a rich REST API, which can be used by external tools in order to perform start/stop/reinitialize/restarts/reloads, by any kind of tools to perform HTTP health checks, and of course, could also be used for monitoring.

Below you will find the list of pg_timetable REST API endpoints.

J.3.6.1.1. Health check endpoints #
J.3.6.1.1.1. GET /liveness #

Always returns HTTP status code 200, indicating that pg_timetable is running.

J.3.6.1.1.2. GET /readiness #

Returns HTTP status code 200 when the pg_timetable is running, and the scheduler is in the main loop processing chains. If the scheduler connects to the database, creates the database schema, or upgrades it, it will return the HTTP status code 503.

J.3.6.1.2. Chain management endpoints #
J.3.6.1.2.1. GET /startchain?id=<chain-id> #

Returns HTTP status code 200 if the chain with the given id can be added to the worker queue. It doesn't, however, mean the chain execution starts immediately. It is up to the worker to perform load and other checks before starting the chain. In the case of an error, the HTTP status code 400 followed by an error message returned.

J.3.6.1.2.2. GET /stopchain?id=<chain-id> #

Returns HTTP status code 200 if the chain with the given id is working at the moment and can be stopped. If the chain is running the cancel signal would be sent immediately. In the case of an error, the HTTP status code 400 followed by an error message returned.

J.3.6.2. Command-Line Reference #

Complete list of pg_timetable command-line flags and their environment-variable equivalents.

# ./pg_timetable

Application Options:
  -c, --clientname=                                Unique name for application instance [$PGTT_CLIENTNAME]
      --config=                                    YAML configuration file
      --no-program-tasks                           Disable executing of PROGRAM tasks [$PGTT_NOPROGRAMTASKS]
  -v, --version                                    Output detailed version information [$PGTT_VERSION]
      --connstr                                    PostgreSQL connection string [$PGTT_CONNSTR]

Logging:
      --log-level=[debug|info|error]               Verbosity level for stdout and log file (default: info)
      --log-database-level=[debug|info|error|none] Verbosity level for database storing (default: info)
      --log-file=                                  File name to store logs
      --log-file-format=[json|text]                Format of file logs (default: json)
      --log-file-rotate                            Rotate log files
      --log-file-size=                             Maximum size in MB of the log file before it gets rotated (default: 100)
      --log-file-age=                              Number of days to retain old log files, 0 means forever (default: 0)
      --log-file-number=                           Maximum number of old log files to retain, 0 to retain all (default: 0)

Start:
  -f, --file=                                      SQL script or YAML chain definition file to execute during
                                                   startup; may be specified multiple times
      --replace                                    Replace existing chains when loading YAML files
      --validate                                   Only validate YAML file without importing chains
      --init                                       Initialize database schema to the latest version and exit. Can be used
                                                   with --upgrade
      --upgrade                                    Upgrade database to the latest version
      --debug                                      Run in debug mode. Only asynchronous chains will be executed

Resource:
      --cron-workers=                              Number of parallel workers for scheduled chains (default: 16)
      --interval-workers=                          Number of parallel workers for interval chains (default: 16)
      --chain-timeout=                             Abort any chain that takes more than the specified number of
                                                   milliseconds
      --task-timeout=                              Abort any task within a chain that takes more than the specified number
                                                   of milliseconds

REST:
      --rest-port=                                 REST API port (default: 0) [$PGTT_RESTPORT]

OTel:
      --otel-endpoint=                             OTLP exporter endpoint URL (grpc://, http://, https://)
      --otel-traces                                Enable OpenTelemetry distributed tracing
      --otel-metrics                               Enable OpenTelemetry metrics export
      --otel-service-name=                         OTel service.name resource attribute (default: pg_timetable)
      --otel-insecure                              Disable TLS for OTLP connection (dev/test only)
      --otel-sample-ratio=                         Trace sampling ratio 0.0-1.0 (default: 1.0)
      --otel-metric-period=                        Metrics export interval in seconds (default: 30)
      --otel-shutdown-timeout=                     OTel provider flush timeout in seconds on shutdown (default: 5)

J.3.6.3. Commands, Tasks, and Chains Reference #

J.3.6.3.1. Command #

Currently, there are three different kinds of commands:

J.3.6.3.1.1. SQL #

SQL snippet. Starting a cleanup, refreshing a materialized view or processing data.

J.3.6.3.1.2. PROGRAM #

External Command. Anything that can be called as an external binary, including shells, e.g. bash, pwsh, etc. The external command will be called using golang's exec.CommandContext.

J.3.6.3.1.3. BUILTIN #

Internal Command. A prebuilt functionality included in pg_timetable. These include:

  • NoOp

  • Sleep

  • Log

  • SendMail

  • Download

  • CopyFromFile

  • CopyToFile

  • CopyFromProgram

  • CopyToProgram

  • Shutdown

J.3.6.3.2. Task #

The next building block is a task, which simply represents a step in a list of chain commands. An example of tasks combined in a chain would be:

  1. Download files from a server

  2. Import files

  3. Run aggregations

  4. Build report

  5. Remove the files from disk

Note

All tasks of the chain in pg_timetable are executed within one transaction. However, please, pay attention there is no opportunity to rollback PROGRAM and BUILTIN tasks.

J.3.6.3.2.1. Table timetable.task #
FieldTypeDescription
chain_idbigintLink to the chain, if NULL task considered to be disabled
task_orderDOUBLE PRECISIONIndicates the order of task within a chain
kindtimetable.command_kindThe type of the command. Can be SQL (default), PROGRAM or BUILTIN
commandtextContains either a SQL command, a path to application or name of the BUILTIN command which will be executed
run_astextThe role as which the task should be executed as
database_connectiontextThe connection string for the external database that should be used
ignore_errorbooleanSpecify if the next task should proceed after encountering an error (default: false)
autonomousbooleanSpecify if the task should be executed out of the chain transaction. Useful for VACUUM, CREATE DATABASE, CALL etc.
timeoutintegerAbort any task within a chain that takes more than the specified number of milliseconds
livebooleanIndication that the task is ready to run, set to false to skip execution (default: true)

Setting live = FALSE on a task row skips its execution without deleting it:

UPDATE timetable.task
SET live = FALSE
WHERE task_id = 42;

The same effect on YAML-managed chains is available via live: false on an individual task.

Warning

If the task has been configured with ignore_error set to true (the default value is false), the worker process will report a success on execution even if the task within the chain fails.

As mentioned above, commands are simple skeletons (e.g. send email, vacuum, etc.). In most cases, they have to be brought to live by passing input parameters to the execution.

J.3.6.3.2.2. Table timetable.parameter #
FieldTypeDescription
task_idbigintThe ID of the task
order_idintegerThe order of the parameter. Several parameters are processed one by one according to the order
valuejsonbA JSON value containing the parameters
J.3.6.3.2.3. Parameter value format #

Depending on the command kind argument can be represented by different JSON values.

J.3.6.3.2.4. SQL #

Schema: array

Example:

'[ "one", 2, 3.14, false ]'::jsonb
J.3.6.3.2.5. PROGRAM #

Schema: array of strings

Example:

'["-x", "Latin-ASCII", "-o", "orte_ansi.txt", "orte.txt"]'::jsonb
J.3.6.3.2.6. BUILTIN: Sleep #

Schema: integer

Example:

'5' :: jsonb
J.3.6.3.2.7. BUILTIN: Log #

Schema: any

Examples:

'"WARNING"'::jsonb
'{"Status": "WARNING"}'::jsonb
J.3.6.3.2.8. BUILTIN: SendMail #

Schema: object

Example:

'{
    "username":     "user@example.com",
    "password":     "password",
    "serverhost":   "smtp.example.com",
    "serverport":   587,
    "senderaddr":   "user@example.com",
    "ccaddr":       ["recipient_cc@example.com"],
    "bccaddr":      ["recipient_bcc@example.com"],
    "toaddr":       ["recipient@example.com"],
    "subject":      "pg_timetable - No Reply",
    "attachment":   ["/temp/attachments/Report.pdf","config.yaml"],
    "attachmentdata": [{"name": "File.txt", "base64data": "RmlsZSBDb250ZW50"}],
    "msgbody":      "<h2>Hello User,</h2> <p>check some attachments!</p>",
    "contenttype":   "text/html; charset=UTF-8"
}'::jsonb
J.3.6.3.2.9. BUILTIN: Download #

Schema: object

Example:

'{
    "workersnum": 2, 
    "fileurls": ["http://example.com/foo.gz", "https://example.com/bar.csv"], 
    "destpath": "."
}'::jsonb
J.3.6.3.2.10. BUILTIN: CopyFromFile #

Schema: object

Example:

'{
    "sql": "COPY location FROM STDIN", 
    "filename": "download/orte_ansi.txt" 
}'::jsonb
J.3.6.3.2.11. BUILTIN: CopyToFile #

Schema: object

Example:

'{
    "sql": "COPY location TO STDOUT", 
    "filename": "download/location.txt" 
}'::jsonb
J.3.6.3.2.12. BUILTIN: CopyToProgram #

Schema: object

Example:

'{
    "sql": "COPY location TO STDOUT",
    "cmd": "sh",
    "args": ["gzip", "-c", ">", "/tmp/output.gz"]
}'::jsonb
J.3.6.3.2.13. BUILTIN: CopyFromProgram #

Schema: object

Example:

'{
    "sql": "COPY location FROM STDIN",
    "cmd": "gunzip",
    "args": ["-c", "/tmp/data.gz"]
}'::jsonb
J.3.6.3.2.14. BUILTIN: Shutdown #

value ignored

J.3.6.3.2.15. BUILTIN: NoOp #

value ignored

J.3.6.3.3. Chain #

Once tasks have been arranged, they have to be scheduled as a chain. For this, pg_timetable builds upon the enhanced cron-string, all the while adding multiple configuration options.

J.3.6.3.3.1. Table timetable.chain #
FieldTypeDescription
chain_nametextThe unique name of the chain
run_attimetable.cronStandard cron-style value at Postgres server time zone or @after, @every, @reboot clause. If NULL, the chain runs every minute
max_instancesintegerThe amount of instances that this chain may have running at the same time
timeoutintegerAbort any chain that takes more than the specified number of milliseconds
livebooleanControl if the chain may be executed once it reaches its schedule
self_destructbooleanSelf destruct the chain after successful execution. Failed chains will be executed according to the schedule one more time
exclusive_executionbooleanSpecifies whether the chain should be executed exclusively while all other chains are paused
client_nametextSpecifies which client should execute the chain. Set this to NULL to allow any client
on_error—Holds SQL to execute if an error occurs. If task produced an error is marked with ignore_error then nothing is done

Note

All chains in pg_timetable are scheduled at the Tantor SE-1C server time zone. You can change the timezone for the current session when adding new chains, e.g.

SET TIME ZONE 'UTC';

-- Run VACUUM at 00:05 every day in August UTC
SELECT timetable.add_job('execute-func', '5 0 * 8 *', 'VACUUM');

J.3.6.4. YAML Chain Definition Format for pg_timetable #

This document defines the YAML format for defining chains of scheduled tasks in pg_timetable.

J.3.6.4.1. YAML Schema #
# Top-level structure
chains:
  - name: "chain-name"                        # Required: chain_name (TEXT, unique)
    schedule: "* * * * *"                     # Required: run_at (cron format)
    live: true                                # Optional: live (BOOLEAN), default: false
    max_instances: 1                          # Optional: max_instances (INTEGER)
    timeout: 30000                            # Optional: timeout in milliseconds (INTEGER)
    self_destruct: false                      # Optional: self_destruct (BOOLEAN), default: false
    exclusive: false                          # Optional: exclusive_execution (BOOLEAN), default: false  
    client_name: "worker-1"                   # Optional: client_name (TEXT)
    on_error: "SELECT log_error()"            # Optional: on_error SQL (TEXT)
    
    tasks:                                                # Required: array of tasks
      - name: "task-1"                                    # Optional: task_name (TEXT)
        kind: "SQL"                                       # Optional: kind (SQL|PROGRAM|BUILTIN), default: SQL
        command: "SELECT $1, $2"                          # Required: command (TEXT)
        parameters:                                       # Optional: parameters (array of execution parameters)
          - ["value1", 42]                                # First execution with these parameters
          - ["value2", 99]                                # Second execution with different parameters
        run_as: "postgres"                                # Optional: run_as (TEXT) - role for SET ROLE
        connect_string: "postgresql://user@host/otherdb"  # Optional: database_connection (TEXT)
        ignore_error: false                               # Optional: ignore_error (BOOLEAN), default: false
        autonomous: false                                 # Optional: autonomous (BOOLEAN), default: false
        timeout: 5000                                     # Optional: timeout in milliseconds (INTEGER)
        live: true                                        # Optional: live (BOOLEAN), default: true; set false to skip the task
        
      - name: "task-2"
        kind: "PROGRAM"
        command: "bash"
        parameters: ["-c", "echo hello"]
        ignore_error: true
J.3.6.4.2. Field Mappings #
J.3.6.4.2.1. Chain Level #
YAML FieldDB ColumnTypeDefaultDescription
namechain_nameTEXTrequiredUnique chain identifier
schedulerun_atcronrequiredCron-style schedule. If omitted or empty, defaults to * * * * * (every minute)
liveliveBOOLEANfalseWhether chain is active
max_instancesmax_instancesINTEGERnullMax parallel instances
timeouttimeoutINTEGER0Chain timeout (ms)
self_destructself_destructBOOLEANfalseDelete after success
exclusiveexclusive_executionBOOLEANfalsePause other chains
client_nameclient_nameTEXTnullRestrict to specific client
on_erroron_errorTEXTnullError handling SQL
J.3.6.4.2.2. Task Level #
YAML FieldDB ColumnTypeDefaultDescription
nametask_nameTEXTnullTask description
kindkindENUM'SQL'Command type (SQL/PROGRAM/BUILTIN)
commandcommandTEXTrequiredCommand to execute
parametersvia timetable.parameterArray of anynullArray of parameter values stored as individual JSONB rows with order_id
run_asrun_asTEXTnullRole for SET ROLE
connect_stringdatabase_connectionTEXTnullConnection string
ignore_errorignore_errorBOOLEANfalseContinue on error
autonomousautonomousBOOLEANfalseExecute outside transaction
timeouttimeoutINTEGER0Task timeout (ms)
liveliveBOOLEANtrueWhether task is executed; disabled tasks are skipped
J.3.6.4.3. Task Ordering #

Tasks are ordered sequentially within a chain based on their array position. The system will automatically assign appropriate task_order values with spacing (e.g., 10, 20, 30) to allow future insertions.

J.3.6.4.4. Examples #
J.3.6.4.4.1. Simple SQL Job #
chains:
  - name: "daily-report"
    schedule: "0 9 * * *"  # 9 AM daily
    live: true
    tasks:
      - name: "generate-report"
        command: "CALL generate_daily_report()"
J.3.6.4.4.2. Multi-task Chain #
chains:
  - name: "etl-pipeline"
    schedule: "0 2 * * *"  # 2 AM daily
    live: true
    max_instances: 1
    timeout: 3600000  # 1 hour
    
    tasks:
      - name: "extract-data"
        command: "SELECT extract_sales_data($1)"
        parameters: ["2023-01-01"]
        
      - name: "transform-data"  
        command: "CALL transform_sales_data()"
        autonomous: true
        
      - name: "load-data"
        command: "CALL load_to_warehouse()"
        ignore_error: false
J.3.6.4.4.3. Program Task #
chains:
  - name: "backup-job"
    schedule: "0 3 * * 0"  # Sunday 3 AM
    live: true
    
    tasks:
      - name: "pg-dump"
        kind: "PROGRAM"
        command: "pg_dump"
        parameters: 
          - ["-h", "localhost", "-U", "postgres", "-d", "mydb", "-f", "/backups/mydb.sql"]
J.3.6.4.5. Validation Rules #
  1. Required Fields: name, schedule, tasks, and command for each task

  2. Unique Names: Chain names must be unique across the database

  3. Valid Cron: Schedule must be valid cron format (5 fields)

  4. Valid Kind: Task kind must be one of: SQL, PROGRAM, BUILTIN

  5. Parameter Types: Parameters can be any JSON-compatible type (strings, numbers, booleans, arrays, objects) and are stored as individual JSONB values

  6. Timeout Values: Must be non-negative integers (milliseconds)

J.3.6.5. Database Schema #

pg_timetable is a database driven application. During the first start the necessary schema is created if absent.

J.3.6.5.1. Main tables and objects #
CREATE TABLE timetable.chain (
    chain_id            BIGSERIAL   PRIMARY KEY,
    chain_name          TEXT        NOT NULL UNIQUE,
    run_at              timetable.cron,
    max_instances       INTEGER,
    timeout             INTEGER     DEFAULT 0,
    live                BOOLEAN     DEFAULT FALSE,
    self_destruct       BOOLEAN     DEFAULT FALSE,
    exclusive_execution BOOLEAN     DEFAULT FALSE,
    client_name         TEXT,
    on_error            TEXT
);

COMMENT ON TABLE timetable.chain IS
    'Stores information about chains schedule';
COMMENT ON COLUMN timetable.chain.run_at IS
    'Extended CRON-style time notation the chain has to be run at';
COMMENT ON COLUMN timetable.chain.max_instances IS
    'Number of instances (clients) this chain can run in parallel';
COMMENT ON COLUMN timetable.chain.timeout IS
    'Abort any chain that takes more than the specified number of milliseconds';
COMMENT ON COLUMN timetable.chain.live IS
    'Indication that the chain is ready to run, set to FALSE to pause execution';
COMMENT ON COLUMN timetable.chain.self_destruct IS
    'Indication that this chain will delete itself after successful run';
COMMENT ON COLUMN timetable.chain.exclusive_execution IS
    'All parallel chains should be paused while executing this chain';
COMMENT ON COLUMN timetable.chain.client_name IS
    'Only client with this name is allowed to run this chain, set to NULL to allow any client';    

CREATE TYPE timetable.command_kind AS ENUM ('SQL', 'PROGRAM', 'BUILTIN');

CREATE TABLE timetable.task (
    task_id             BIGSERIAL               PRIMARY KEY,
    chain_id            BIGINT                  REFERENCES timetable.chain(chain_id) ON UPDATE CASCADE ON DELETE CASCADE,
    task_order          DOUBLE PRECISION        NOT NULL,
    task_name           TEXT,
    kind                timetable.command_kind  NOT NULL DEFAULT 'SQL',
    command             TEXT                    NOT NULL,
    run_as              TEXT,
    database_connection TEXT,
    ignore_error        BOOLEAN                 NOT NULL DEFAULT FALSE,
    autonomous          BOOLEAN                 NOT NULL DEFAULT FALSE,
    timeout             INTEGER                 DEFAULT 0,
    live                BOOLEAN                 NOT NULL DEFAULT TRUE
);          

COMMENT ON TABLE timetable.task IS
    'Holds information about chain elements aka tasks';
COMMENT ON COLUMN timetable.task.chain_id IS
    'Link to the chain, if NULL task considered to be disabled';
COMMENT ON COLUMN timetable.task.task_order IS
    'Indicates the order of task within a chain';    
COMMENT ON COLUMN timetable.task.run_as IS
    'Role name to run task as. Uses SET ROLE for SQL commands';
COMMENT ON COLUMN timetable.task.ignore_error IS
    'Indicates whether a next task in a chain can be executed regardless of the success of the current one';
COMMENT ON COLUMN timetable.task.kind IS
    'Indicates whether "command" is SQL, built-in function or an external program';
COMMENT ON COLUMN timetable.task.command IS
    'Contains either an SQL command, or command string to be executed';
COMMENT ON COLUMN timetable.task.timeout IS
    'Abort any task within a chain that takes more than the specified number of milliseconds';
COMMENT ON COLUMN timetable.task.autonomous IS
    'Specify if the task should be executed out of the chain transaction. Useful for VACUUM, CREATE DATABASE, CALL etc.';
COMMENT ON COLUMN timetable.task.live IS
    'Indication that the task is ready to run, set to FALSE to skip execution';

-- parameter passing for a chain task
CREATE TABLE timetable.parameter(
    task_id     BIGINT  REFERENCES timetable.task(task_id)
                        ON UPDATE CASCADE ON DELETE CASCADE,
    order_id    INTEGER CHECK (order_id > 0),
    value       JSONB,
    PRIMARY KEY (task_id, order_id)
);

COMMENT ON TABLE timetable.parameter IS
    'Stores parameters passed as arguments to a chain task';

CREATE UNLOGGED TABLE timetable.active_session(
    client_pid  BIGINT  NOT NULL,
    server_pid  BIGINT  NOT NULL,
    client_name TEXT    NOT NULL,
    started_at  TIMESTAMPTZ DEFAULT now()
);

COMMENT ON TABLE timetable.active_session IS
    'Stores information about active sessions';

CREATE TYPE timetable.log_type AS ENUM ('DEBUG', 'NOTICE', 'INFO', 'ERROR', 'PANIC', 'USER');

CREATE OR REPLACE FUNCTION timetable.get_client_name(integer) RETURNS TEXT AS
$$
    SELECT client_name FROM timetable.active_session WHERE server_pid = $1 LIMIT 1
$$
LANGUAGE sql;

CREATE TABLE timetable.log
(
    ts              TIMESTAMPTZ         DEFAULT now(),
    pid             INTEGER             NOT NULL,
    log_level       timetable.log_type  NOT NULL,
    client_name     TEXT                DEFAULT timetable.get_client_name(pg_backend_pid()),
    message         TEXT,
    message_data    jsonb
);

COMMENT ON TABLE timetable.log IS
    'Stores log entries of active sessions';

CREATE TABLE timetable.execution_log (
    chain_id        BIGINT,
    task_id         BIGINT,
    txid            BIGINT NOT NULL,
    last_run        TIMESTAMPTZ DEFAULT now(),
    finished        TIMESTAMPTZ,
    pid             BIGINT,
    returncode      INTEGER,
    ignore_error    BOOLEAN,
    kind            timetable.command_kind,
    command         TEXT,
    output          TEXT,
    client_name     TEXT        NOT NULL,
    params          TEXT
);

COMMENT ON TABLE timetable.execution_log IS
    'Stores log entries of executed tasks and chains';
COMMENT ON COLUMN timetable.execution_log.chain_id IS
    'Link to the chain executed';
COMMENT ON COLUMN timetable.execution_log.task_id IS
    'Link to the task executed';
COMMENT ON COLUMN timetable.execution_log.txid IS
    'Transaction ID of the executed task';
COMMENT ON COLUMN timetable.execution_log.last_run IS
    'Timestamp of the last execution of the task';
COMMENT ON COLUMN timetable.execution_log.finished IS
    'Timestamp of the task execution finish';
COMMENT ON COLUMN timetable.execution_log.pid IS
    'Process ID of the worker executing the task';
COMMENT ON COLUMN timetable.execution_log.returncode IS
    'Return code of the executed task';
COMMENT ON COLUMN timetable.execution_log.ignore_error IS
    'Indicates whether a next task in a chain can be executed regardless of the success of the current one';
COMMENT ON COLUMN timetable.execution_log.kind IS
    'Indicates whether "command" is SQL, built-in function or an external program';
COMMENT ON COLUMN timetable.execution_log.command IS
    'Contains either an SQL command, or command string to be executed';
COMMENT ON COLUMN timetable.execution_log.output IS
    'Contains output of the executed task';
COMMENT ON COLUMN timetable.execution_log.client_name IS
    'Name of the client executing the task';
COMMENT ON COLUMN timetable.execution_log.params IS
    'Contains parameters passed as arguments to a chain task';

CREATE INDEX execution_log_chain_id_finished_idx
    ON timetable.execution_log (chain_id, finished);

CREATE INDEX execution_log_finished_brin_idx
    ON timetable.execution_log USING brin (finished);

CREATE UNLOGGED TABLE timetable.active_chain(
    chain_id    BIGINT  NOT NULL,
    client_name TEXT    NOT NULL,
    started_at  TIMESTAMPTZ DEFAULT now()
);

COMMENT ON TABLE timetable.active_chain IS
    'Stores information about active chains within session';

CREATE OR REPLACE FUNCTION timetable.try_lock_client_name(worker_pid BIGINT, worker_name TEXT)
RETURNS bool AS
$CODE$
BEGIN
    IF pg_is_in_recovery() THEN
        RAISE NOTICE 'Cannot obtain lock on a replica. Please, use the primary node';
        RETURN FALSE;
    END IF;
    -- remove disconnected sessions
    DELETE
        FROM timetable.active_session
        WHERE server_pid NOT IN (
            SELECT pid
            FROM pg_catalog.pg_stat_activity
            WHERE application_name = 'pg_timetable'
        );
    DELETE 
        FROM timetable.active_chain 
        WHERE client_name NOT IN (
            SELECT client_name FROM timetable.active_session
        );
    -- check if there any active sessions with the client name but different client pid
    PERFORM 1
        FROM timetable.active_session s
        WHERE
            s.client_pid <> worker_pid
            AND s.client_name = worker_name
        LIMIT 1;
    IF FOUND THEN
        RAISE NOTICE 'Another client is already connected to server with name: %', worker_name;
        RETURN FALSE;
    END IF;
    -- insert current session information
    INSERT INTO timetable.active_session(client_pid, client_name, server_pid) VALUES (worker_pid, worker_name, pg_backend_pid());
    RETURN TRUE;
END;
$CODE$
STRICT
LANGUAGE plpgsql;

J.3.6.6. Secret Store #

The secret store is introduced by migration 00820 and lives entirely in the timetable schema. The schema applies unchanged on a database without pgcrypto installed; the extension is needed only by sessions that actually resolve a secret.

For the write-only design rationale and the threat model this raises the bar against, see Secret Store Security Model.

J.3.6.6.1. pgcrypto is an optional prerequisite #

pg_timetable never installs, requires, or probes for pgcrypto. The migration and the timetable schema both apply cleanly on a database without pgcrypto and whose role could not install one. The extension is the responsibility of the database administrator; the only place it is looked up is inside timetable.resolve_secret() at call time.

J.3.6.6.2. Schema objects #

The table and function definitions appear via the ddl.sql pymdownx snippet above. In summary:

  • timetable.secret(client_name TEXT NOT NULL, secret_name TEXT NOT NULL, value_enc BYTEA NOT NULL, created_at / updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_by TEXT NOT NULL DEFAULT session_user). PRIMARY KEY (client_name, secret_name) — no surrogate secret_id. CHECK (secret_name ~ '^[A-Za-z0-9_.-]+$'). REVOKE ALL FROM PUBLIC; no default grants to other roles.

  • timetable.secret_touch() — BEFORE UPDATE trigger that refreshes updated_at / updated_by so manual UPDATEs cannot leave stale audit data. Created with EXECUTE PROCEDURE (compatible with every Tantor SE-1C in the supported matrix) and a plain CREATE TRIGGER.

  • timetable.resolve_secret(p_name TEXT, p_client TEXT, p_key TEXT) RETURNS TEXT — LANGUAGE plpgsql, SECURITY DEFINER, STRICT, STABLE, SET search_path = pg_catalog, timetable. The pgcrypto lookup and the decrypt call live in dynamic SQL. The function locates the extension's schema at call time from pg_catalog.pg_extension / pg_catalog.pg_namespace, so public, a private schema, and a schema set via ALTER EXTENSION pgcrypto SET SCHEMA ... all work. Returns NULL when the (client_name, secret_name) pair does not exist (without requiring pgcrypto). Raises feature_not_supported (SQLSTATE 0A000) when pgcrypto is absent — that single task fails, the scheduler keeps running. Raises Wrong key or corrupt data on a wrong key. LANGUAGE plpgsql is required (not LANGUAGE sql) so the function creates successfully on a database without pgcrypto.

  • timetable.secret_count() RETURNS BIGINT — LANGUAGE sql, SECURITY DEFINER, STABLE. Returns count(*) over timetable.secret. Used by the scheduler startup check when no encryption key is configured; does not require pgcrypto. Returns 0 when no secrets exist, including on a database without pgcrypto installed.

J.3.6.6.3. Reference syntax #

${secret:name} in timetable.parameter.value (jsonb string leaves) or timetable.task.database_connection is replaced at execution time with the decrypted value of the matching timetable.secret row for the running client. Resolved values are masked from execution_log.params, timetable.log, and the pgx tracer's args field; see the masking contract in the spec.

The store is opt-in syntax. Chains created before this feature, whose parameter.value holds a literal password, continue to work unchanged.

J.3.6.6.4. Permission model #
  • PUBLIC has no privileges on the table or the functions.

  • The owning role (the scheduler's connection role) can read value_enc directly — the key, not the grant model, is the confidentiality boundary.

  • No new role is created by the schema. Operators who want a separate secret-administration role must GRANT INSERT, UPDATE, DELETE ON timetable.secret TO admin_role themselves; this is an operator step, not a schema-managed role.

  • The scheduler startup check (CheckSecretConfig) calls timetable.secret_count() exactly once when the encryption key is unset, and skips it entirely when the key is set. A failure of the check itself is logged, never fatal.

J.3.6.7. OpenTelemetry Reference #

OTel command-line flags are documented in the Command-Line Reference.

J.3.6.7.1. Protocol Selection #

The OTLP transport protocol is inferred automatically from the endpoint URL scheme:

SchemeTransport
grpc://OTLP/gRPC
http://OTLP/HTTP (protobuf)
https://OTLP/HTTP with TLS

TLS is enabled by default for all transports. Use --otel-insecure to disable TLS verification in development environments.

J.3.6.7.2. Trace Schema #

Each chain execution produces a root span chain.execute containing child spans task.execute for every task in the chain.

J.3.6.7.2.1. Span: chain.execute #
AttributeValue
chain.idChain ID (integer)
chain.nameChain name
client.namepg_timetable client name (--clientname)
J.3.6.7.2.2. Span: task.execute #
AttributeValue
task.nameTask command
task.kindSQL, PROGRAM, or BUILTIN
task.return_code0 on success, -1 on failure

Failed tasks produce an OTel error event with the error message, allowing trace-based alerting and root-cause analysis.

J.3.6.7.3. Metric Instruments #

All instruments are registered under the meter name pg_timetable and carry the client.name attribute for multi-instance deployments.

InstrumentKindUnitDescription
pgtimetable.chain.startedCounter{execution}Chain executions started
pgtimetable.chain.completedCounter{execution}Chain executions completed successfully
pgtimetable.chain.failedCounter{execution}Chain executions that failed
pgtimetable.chain.durationHistogramsWall-clock duration of chain execution
pgtimetable.task.executedCounter{execution}Tasks executed (labelled by task.kind)

The histogram uses these explicit bucket boundaries (seconds): 0.001, 0.01, 0.1, 0.5, 1, 5, 10, 30, 60, 120, 300

J.3.6.7.4. Authentication & Security #

SaaS observability backends (Honeycomb, Grafana Cloud, Datadog, etc.) typically require an API key. Pass it as a custom HTTP header via the YAML configuration file:

otel:
  endpoint: https://api.honeycomb.io
  traces: true
  headers:
    x-honeycomb-team: YOUR_API_KEY

Warning

otel.headers can only be set via the YAML configuration file — it is not available as a CLI flag to prevent API keys from appearing in shell history or process listings. Header values are never written to log output.

J.3.6.7.5. Sampling Ratio #
ValueEffect
1.0 (default)Every chain execution is traced
0.5~50 % of executions traced
0.0No traces generated
J.3.6.7.6. Resilience #
  • Unreachable backend: pg_timetable starts normally and logs a WARN message. Chain scheduling is never interrupted by OTel export failures.

  • Graceful shutdown: On SIGTERM, pg_timetable flushes pending spans and metrics before exiting. The flush timeout is controlled by --otel-shutdown-timeout (default: 5 s).

J.3.6.7.7. YAML Configuration #
# - OpenTelemetry Settings -
otel:
  # OTLP exporter endpoint URL (grpc://, http://, https://)
  endpoint: ""

  # Enable distributed tracing (default: false)
  traces: false

  # Enable metrics export (default: false)
  metrics: false

  # OTel service.name resource attribute (default: pg_timetable)
  service-name: pg_timetable

  # Custom headers for OTLP export — use for API key auth (map of key: value)
  headers: {}

  # Disable TLS for OTLP connection — dev only (default: false)
  insecure: false

  # Trace sampling ratio 0.0–1.0 (default: 1.0 = 100%)
  sample-ratio: 1.0

  # Metrics export interval in seconds (default: 30)
  metric-period: 30

  # OTel flush timeout in seconds on shutdown (default: 5)
  shutdown-timeout: 5
J.3.6.7.8. OTel Resource Attributes #

Every span and metric datapoint carries these resource attributes identifying the pg_timetable instance:

AttributeValue
service.name--otel-service-name (default: pg_timetable)
service.versionpg_timetable binary version
client.name--clientname value

J.3.7. Concepts #

J.3.7.1. The Scheduling Model #

The scheduling in pg_timetable encompasses three different abstraction levels to facilitate the reuse with other parameters or additional schedules.

Command: The base level, command, defines what to do.

Task: The second level, task, represents a chain element (step) to run one of the commands. With tasks we define order of commands, arguments passed (if any), and how errors are handled.

Chain: The third level represents connected tasks forming a chain of tasks. Chain defines if, when, and how often a job should be executed. A chain with a NULL schedule (no run_at value) is started at every scheduler loop tick — every 60 seconds by default — so it effectively runs every minute.

Note

If a chain's run_at (schedule) is NULL, it will execute on every scheduler tick (by default, every minute). This is equivalent to a * * * * * cron schedule.

The exact fields, kinds, and parameter formats for each level are documented in the Commands, Tasks, and Chains Reference.

J.3.7.2. Design Philosophy #

pg_timetable was created to solve a recurring set of operational frustrations with existing Tantor SE-1C schedulers. It is not merely another cron-in-the-database — it is an opinionated orchestration engine designed around a few core beliefs about how database automation should work.

J.3.7.2.1. Chains, Not Cron #

Traditional schedulers — pg_cron, pgAgent, even OS-level cron — follow the "fire and forget" model: at a given time, run a given command, done. This works for VACUUM at midnight, but it breaks down as soon as you need sequencing: run an ETL extract, wait, transform, wait, load, wait, then send a success email. Or, on failure, send an alert instead and skip the subsequent steps.

pg_timetable's fundamental unit is the chain: an ordered sequence of tasks where each step's outcome determines what happens next. A task can point to another task to run on success, and a different one on error. This turns scheduling into workflow orchestration — you are not just triggering isolated statements; you are defining control flow that lives in the database alongside your data.

The chain model also enables autonomous tasks: a step that fires and detaches, letting the chain continue without waiting. This is not a cron concept at all — it is an admission that real-world automation often involves steps whose completion is irrelevant to the parent workflow.

J.3.7.2.2. Database-Driven, Not Database-Locked #

Every Tantor SE-1C scheduler stores job metadata in the database. But most require a Tantor SE-1C extension, which means shared_preload_libraries, a server restart, and a dependency on a specific Tantor SE-1C major version.

pg_timetable is a standalone Go binary. It connects to Tantor SE-1C like any other client — over libpq, with a connection string. No extension to install, no server restart, no coupling to a single Tantor SE-1C version or deployment model. If you can psql into it, pg_timetable can schedule on it.

This architecture has a second, more subtle consequence: remote database execution. A single pg_timetable instance can schedule jobs across multiple Tantor SE-1C servers, including servers on different hosts, different versions, and different cloud providers. Most competitors are either restricted to the local server (pg_cron, as a background worker) or can reach remote hosts but require complex setup (pgAgent). pg_timetable treats every connection string as a peer — a first-class scheduling target with its own chains, its own execution context, and its own logging namespace.

Being in Go rather than C or C++ also means a single statically-linked binary that runs identically on Linux, macOS, Windows, and every BSD — no runtime, no dynamic linking surprises, no compiler toolchain required for deployment.

J.3.7.2.3. Batteries Included #

pg_timetable accumulates features that other Tantor SE-1C schedulers leave to external tooling. This is deliberate.

Built-in tasks. Only pg_timetable ships with predefined operations — SendMail, Download, CopyFromFile, Sleep, Log, and more — that are directly addressable as chain steps. You do not need to escape to a shell script to send an email when an ETL chain fails; you add a SendMail task with the right parameters and wire it to the error path.

Task parameters. Only pg_timetable supports parameterized tasks. A my_func($1, $2) definition can receive different arguments depending on the chain that invokes it, which enables task reuse across chains without duplication. Combined with the YAML or JSON COMMAND_CONFIG format, this also means built-in tasks accept structured configuration — not opaque shell strings.

Granular logging. Other schedulers either log to a single destination or leave logging details undocumented. pg_timetable logs at three levels (session, job, task) to three destinations simultaneously: stdout/stderr, file, and database tables. The database logger writes structured rows to timetable.log, which means execution history is queryable with SQL — you can SELECT your scheduler's audit trail with the same tool you use to inspect your application data.

Execution control. Job-level and task-level timeouts prevent runaway processes. Concurrency protection (max_instances) prevents overlapping runs of the same chain. Manual start and kill operations enable debugging workflows that most schedulers simply do not support. None of these are glamorous, but their absence is felt immediately in production — and pg_timetable is the only Tantor SE-1C scheduler that provides all of them.

J.3.7.2.4. Operator-First Design #

pg_timetable assumes its primary user is a DBA or operations engineer who already knows cron syntax, already works in SQL, and wants their scheduling configuration to be as version-controllable and reviewable as their schema migrations.

No GUI dependency. pgAgent requires a graphical interface to define schedules — cron syntax is not accepted as input. This is a deliberate inversion: pg_timetable schedules are always expressed as cron expressions, interval strings, or cron-like tokens (@reboot, @every), whether you define them via timetable.add_job() in SQL or via a YAML file. There is no checkbox-to-cron translation layer because there are no checkboxes.

Config-as-code. Chains can be defined in SQL (call add_job() and friends) or in YAML files loaded at startup. Both are plain text, both can live in version control, both can be reviewed in a pull request. The YAML path is the recommended approach for production: it separates scheduling configuration from runtime state, makes bulk updates safe, and integrates naturally with CI/CD pipelines.

Scheduling richness. pg_timetable is the only Tantor SE-1C scheduler supporting standard cron, interval-based scheduling, @reboot execution, manual start, manual kill, job timeouts, task timeouts, job disabling, and self-destructive (run-once-then-delete) jobs — all simultaneously. This is not feature checklisting; it reflects a philosophy that scheduling is a spectrum of operational needs, and the tool should not force you to switch to another scheduler just because your use case changed from "run every Tuesday" to "run once when I restart the scheduler" to "run now because I'm debugging."

J.3.7.2.5. What pg_timetable Is Not #

pg_timetable is not a distributed workflow engine. It does not coordinate chains across multiple scheduler instances, it does not implement leader election, and it does not provide a distributed lock manager. If you need horizontally-scaled job execution with failover, you are looking for something closer to Apache Airflow or Temporal. pg_timetable is designed for the single-scheduler-per-database-cluster operational model that covers the vast majority of Tantor SE-1C deployments.

pg_timetable is not a replacement for OS-level cron when the task has nothing to do with the database. If you are scheduling filesystem cleanup or system reboots, use cron. pg_timetable earns its complexity when the scheduled work touches Tantor SE-1C — directly (SQL tasks), indirectly (shell tasks that connect back to Tantor SE-1C), or operationally (built-in tasks that depend on database state).

pg_timetable is not a monitoring system. It has OpenTelemetry export and database-level logging, but it does not replace Prometheus alert rules or Grafana dashboards. It tells you what it ran and whether it succeeded; you bring the alerting.

J.3.7.2.6. Why Go? Why Standalone? #

The choice of Go as the implementation language was not arbitrary. A Tantor SE-1C scheduler must manage concurrent database connections, long-running task goroutines, timeout enforcement, and signal handling — all of which map naturally to Go's concurrency primitives. A single statically-linked binary eliminates the runtime dependency issues that plague C/C++ schedulers (libpq version drift, compiler ABI changes) and the JVM footprint concerns that make Java-based schedulers heavy for a sidecar process.

The standalone architecture — as opposed to a Tantor SE-1C background worker — means pg_timetable can be deployed as a systemd service, a Docker container, a Kubernetes sidecar, or a Nomad job without touching the Tantor SE-1C server configuration. It also means the scheduler can be restarted, upgraded, or moved to a different host without affecting the database server — a property that matters when the database is a managed cloud service where you cannot modify shared_preload_libraries.

J.3.7.2.7. Further Reading #

J.3.7.3. Secret Store Security Model #

The secret store is write-only by design — there is no plaintext read path; values are encrypted at rest with pgp_sym_encrypt (from the pgcrypto extension), decrypted only by the SECURITY DEFINER function timetable.resolve_secret() when the caller supplies the encryption key, and never exposed back to SQL as plaintext outside the resolved parameter. There is no surrogate secret_id; rows are addressed by (client_name, secret_name) only.

The running scheduler process is the trusted execution boundary. The secret store raises the bar against:

  • other database roles (Grafana, reporting, ad-hoc DBA sessions),

  • logical-replica subscribers, and

  • pg_dump archives taken without the encryption key.

It does not raise the bar against a compromised worker host, ps / auditd argv inspection, or any party that holds both value_enc and the PGTT_SECRET_KEY value. The scheduler's connection role can read value_enc directly; confidentiality rests on possession of the encryption key, which the database never stores.

This feature raises the bar against other database roles, logical replicas, and pg_dump without the key. It does not by itself satisfy any specific regulatory secret-management control (PCI-DSS key custody, SOC 2 rotation).

PROGRAM-tasks (samples/Shell.sql) take a JSON-encoded argv array. Resolved values land in argv, which is observable via /proc/<pid>/cmdline and /proc/<pid>/environ on the worker host. This is a documented trade-off of v1, not a bug.

At --log-level=debug and --log-database-level=debug, the pgx tracer persists query entries to timetable.log. The pgx logger is context-aware: queries executed under log.WithoutQueryArgs(ctx) (the marker used by ResolveSecrets*) drop the args field while retaining sql, so neither the plaintext nor the encryption key reaches timetable.log or the stdout/file log.

execution_log.params is intentionally the unresolved ${secret:name} form.

J.3.7.3.1. Trade-offs Against Alternatives #

.pgpass / .pg_service.conf on the worker host is a better fit than ${secret:...} for remote Postgres passwords: it keeps the credential off the database entirely. The secret store earns its complexity for credentials that have no host-local equivalent, such as SMTP passwords.

Environment variables or stdin are a better fit than ${secret:...} for sensitive PROGRAM-task argv in production: passing the literal ${secret:x} to a child process would be silently wrong (the placeholder string itself, not the secret) rather than loudly unsupported.