You can automate the execution of stored procedures with triggers. A trigger listens to database events and executes its associated stored procedure when the events occur. You can use triggers with CREATE SCHEDULE to implement Scheduled execution.
Individual triggers can be enabled and disabled with ENABLE_TRIGGER, and can be manually executed with EXECUTE_TRIGGER.
1 - Scheduled execution
Stored procedures can be scheduled to execute automatically with the privileges of the trigger definer.
Stored procedures can be scheduled to execute automatically with the privileges of the trigger definer. You can use this to automate various tasks, like logging database activity, revoking privileges, or creating roles.
The following example creates a trigger that revokes privileges on the customer_dimension table from the user Bob after 24 hours:
Create a stored procedure to revoke privileges from Bob:
=> CREATE OR REPLACE PROCEDURE revoke_all_on_table(table_name VARCHAR, user_name VARCHAR)
LANGUAGE PLvSQL
AS $$
BEGIN
EXECUTE 'REVOKE ALL ON ' || QUOTE_IDENT(table_name) || ' FROM ' || QUOTE_IDENT(user_name);
END;
$$;
Create a schedule with a timestamp for 24 hours later:
=> CREATE SCHEDULE 24_hours_later USING DATETIMES('2022-12-16 12:00:00');
Create a trigger with the stored procedure and schedule:
=> CREATE TRIGGER revoke_trigger ON SCHEDULE 24_hours_later EXECUTE PROCEDURE revoke_all_on_table('customer_dimension', 'Bob') AS DEFINER;
Recurring triggers
Recurring triggers run at a recurring date or time.
The following example creates a weekly trigger that logs to the USER_COUNT table the number of users in the database:
=> CREATE OR REPLACE PROCEDURE log_user_count()
LANGUAGE PLvSQL
AS $$
DECLARE
num_users int := SELECT count (user_id) FROM users;
timestamp datetime := SELECT NOW();
BEGIN
PERFORM INSERT INTO USER_COUNT VALUES(num_users, timestamp);
END;
$$;
Create the trigger with the stored procedure and schedule:
=> CREATE TRIGGER user_log_trigger ON SCHEDULE weekly_sunday EXECUTE PROCEDURE log_user_count() AS DEFINER;
Viewing upcoming schedules
Schedules are managed and coordinated by the Active Scheduler Node (ASN). If the ASN goes down, a different node is automatically designated as the new ASN. To view scheduled tasks, query SCHEDULER_TIME_TABLE on the ASN.