Job Scheduler
Use this to create and monitor periodic jobs such as nightly aggregation, purging old data, and statistics gathering. Oracle and SQL Server have a scheduler inside the database (DBMS_SCHEDULER, SQL Server Agent), while PostgreSQL has none by default, so you use the pg_cron extension or the OS cron. Either way, the checks are the same: is the job enabled, did the last run succeed, when is the next run, and are any jobs running too long.
Oracle
Required privileges: CREATE JOB to create in your own schema, CREATE ANY JOB for other schemas. CREATE EXTERNAL JOB for OS commands (EXECUTABLE). DBA_ view privileges for full listings.
Create a job (DBMS_SCHEDULER.CREATE_JOB)
BEGIN
DBMS_SCHEDULER.CREATE_JOB(
job_name => 'APP.NIGHTLY_PURGE',
job_type => 'STORED_PROCEDURE',
job_action => 'APP.PURGE_OLD_ORDERS',
start_date => SYSTIMESTAMP,
repeat_interval => 'FREQ=DAILY; BYHOUR=2; BYMINUTE=0; BYSECOND=0',
enabled => TRUE,
comments => 'Purge orders older than 90 days');
END;
/
job_type:PLSQL_BLOCK(anonymous block),STORED_PROCEDURE,EXECUTABLE(OS command), and so on.repeat_intervalis a calendar expression. Example: on the hour every hour on weekdays,FREQ=HOURLY; BYDAY=MON,TUE,WED,THU,FRI; BYMINUTE=0.- The time zone follows that of
start_date. In regions with daylight saving time, give a region name such asTO_TIMESTAMP_TZ('... Asia/Seoul', ...)instead ofSYSTIMESTAMP. - The old
DBMS_JOBstill runs in 19c, but it has been converted internally to scheduler jobs. UseDBMS_SCHEDULERfor new jobs.
Job list and next run
SELECT owner, job_name, enabled, state, repeat_interval,
last_start_date, last_run_duration, next_run_date,
run_count, failure_count
FROM dba_scheduler_jobs
WHERE owner NOT IN ('SYS', 'SYSTEM', 'ORACLE_OCM')
ORDER BY next_run_date;
state: SCHEDULED (waiting), RUNNING, DISABLED, BROKEN (stopped after consecutive failures, when max_failures is set), COMPLETED.
Run history and failures
SELECT log_date, owner, job_name, status, error#, run_duration, additional_info
FROM dba_scheduler_job_run_details
WHERE log_date > SYSTIMESTAMP - INTERVAL '1' DAY
AND status <> 'SUCCEEDED'
ORDER BY log_date DESC;
error#is the error number, andadditional_infohas the error message (12.2+ also haserrorsandoutputcolumns).- History is kept for
log_history(30 days by default).
Running jobs, manual run and stop
SELECT owner, job_name, session_id, elapsed_time, cpu_used
FROM dba_scheduler_running_jobs;
EXEC DBMS_SCHEDULER.RUN_JOB('APP.NIGHTLY_PURGE', use_current_session => FALSE);
EXEC DBMS_SCHEDULER.STOP_JOB('APP.NIGHTLY_PURGE');
EXEC DBMS_SCHEDULER.DISABLE('APP.NIGHTLY_PURGE');
EXEC DBMS_SCHEDULER.ENABLE('APP.NIGHTLY_PURGE');
WARNING
STOP_JOBrolls back the running job's transaction.force => TRUErequires theMANAGE SCHEDULERprivilege and can kill the job without cleanup, so it is a last resort.DROP_JOBremoves the job definition.
Automated maintenance tasks
Oracle automatically runs statistics gathering and other tasks in the maintenance windows (by default, 22:00 on weekdays and 06:00 on weekends).
SELECT client_name, status FROM dba_autotask_client;
SELECT client_name, window_name, job_start_time, job_duration, job_status
FROM dba_autotask_job_history
WHERE job_start_time > SYSTIMESTAMP - INTERVAL '7' DAY
ORDER BY job_start_time DESC;
SELECT window_name, enabled, active, next_start_date, duration
FROM dba_scheduler_windows;
- Clients:
auto optimizer stats collection(statistics),auto space advisor,sql tuning advisor. - Using the automatic results of
sql tuning advisorrequires a Tuning Pack license. If you do not have the license, keep it disabled.
BEGIN
DBMS_AUTO_TASK_ADMIN.DISABLE(client_name => 'sql tuning advisor',
operation => NULL,
window_name => NULL);
END;
/
WARNING If you disable
auto optimizer stats collection, statistics go stale and execution plans get worse. If you disable it, you must create a separate job that does the same work.
PostgreSQL
The PostgreSQL core has no scheduler. Use one of the two approaches below.
Install pg_cron (a separate extension)
pg_cron is an extension that is not included with PostgreSQL. Install it from a package (for example, postgresql-16-cron), or on managed services such as RDS, Azure, and Cloud SQL, enable it in the parameter group.
# postgresql.conf (restart required)
shared_preload_libraries = 'pg_cron'
cron.database_name = 'postgres' # the database to create the extension in; job metadata lives here
-- In the database named in cron.database_name
CREATE EXTENSION pg_cron;
Create a job
SELECT cron.schedule('nightly-vacuum', '0 3 * * *', 'VACUUM ANALYZE sales.orders');
-- Run in another database (pg_cron 1.4+)
SELECT cron.schedule_in_database('purge-orders', '30 2 * * *',
'CALL app.purge_old_orders()', 'sales');
SELECT cron.unschedule('nightly-vacuum');
- The schedule uses the standard cron format (minute hour day month weekday). The default time zone is GMT (UTC). Recent versions let you change it with
cron.timezone. - Jobs run with the privileges of the role that created them. Calling
cron.scheduleagain with the samejobnamereplaces the existing job.
Job list and run history
SELECT jobid, jobname, schedule, command, database, username, active
FROM cron.job
ORDER BY jobid;
SELECT d.jobid, j.jobname, d.status, d.return_message, d.start_time, d.end_time,
d.end_time - d.start_time AS duration
FROM cron.job_run_details d
JOIN cron.job j ON j.jobid = d.jobid
WHERE d.start_time > now() - interval '1 day'
ORDER BY d.start_time DESC;
status:starting,running,succeeded,failed. On failure,return_messagehas the error.cron.job_run_detailsis not purged automatically. Schedule a cleanup job.
SELECT cron.schedule('purge-cron-history', '0 4 * * *',
$DELETE FROM cron.job_run_details WHERE end_time < now() - interval '14 days'$);
Run from the OS cron
If you cannot install the extension, call psql from the cron of the server or a separate management server (Task Scheduler on Windows).
# crontab -e (postgres account)
0 3 * * * psql -X -q -v ON_ERROR_STOP=1 -d sales -c "VACUUM ANALYZE sales.orders" >> /var/log/pg_jobs/vacuum.log 2>&1
- Do not put the password in the crontab; use
~/.pgpass(permissions 600) or local peer authentication. - Run history is not kept in the database, so monitor for failures through the log file and the exit code.
SQL Server
SQL Server Agent is the scheduler. Express edition has no Agent. On Express, call sqlcmd from Windows Task Scheduler.
Required privileges: sysadmin, or in msdb SQLAgentUserRole (your own jobs), SQLAgentReaderRole (view all jobs), SQLAgentOperatorRole (run and stop all jobs).
Agent service status
SELECT servicename, status_desc, startup_type_desc, last_startup_time
FROM sys.dm_server_services;
If the Agent service is Stopped or its startup type is Manual, no jobs run after a server restart.
Create a job
USE msdb;
EXEC dbo.sp_add_job @job_name = N'Nightly purge', @enabled = 1;
EXEC dbo.sp_add_jobstep @job_name = N'Nightly purge', @step_name = N'purge',
@subsystem = N'TSQL', @database_name = N'sales',
@command = N'EXEC dbo.purge_old_orders;',
@retry_attempts = 1, @retry_interval = 5;
EXEC dbo.sp_add_schedule @schedule_name = N'Daily 02:00',
@freq_type = 4, @freq_interval = 1, -- daily
@active_start_time = 020000; -- HHMMSS
EXEC dbo.sp_attach_schedule @job_name = N'Nightly purge', @schedule_name = N'Daily 02:00';
EXEC dbo.sp_add_jobserver @job_name = N'Nightly purge'; -- run on this server
If you leave out sp_add_jobserver, the job is created but does not run.
Recent failures
SELECT j.name AS job_name, h.step_id, h.step_name,
msdb.dbo.agent_datetime(h.run_date, h.run_time) AS run_at,
h.run_duration, -- integer in HHMMSS format
h.run_status, LEFT(h.message, 400) AS message
FROM msdb.dbo.sysjobhistory h
JOIN msdb.dbo.sysjobs j ON j.job_id = h.job_id
WHERE h.run_status <> 1
AND h.run_date >= CONVERT(int, CONVERT(char(8), DATEADD(DAY, -1, GETDATE()), 112))
ORDER BY run_at DESC;
run_status: 0 failed, 1 succeeded, 2 retry, 3 canceled, 4 in progress.- The row with
step_id = 0is the result of the whole job, and the others are per-step results. - By default, history keeps only 1000 rows in total and 100 rows per job (adjust in the Agent properties, purge with
sp_purge_jobhistory).
Job list, running jobs
EXEC msdb.dbo.sp_help_jobactivity; -- last and next run per job, whether running
-- Currently running jobs and elapsed time
SELECT j.name, a.start_execution_date,
DATEDIFF(MINUTE, a.start_execution_date, GETDATE()) AS running_min
FROM msdb.dbo.sysjobactivity a
JOIN msdb.dbo.sysjobs j ON j.job_id = a.job_id
WHERE a.session_id = (SELECT MAX(session_id) FROM msdb.dbo.syssessions)
AND a.start_execution_date IS NOT NULL
AND a.stop_execution_date IS NULL;
The most recent session_id in syssessions is the current run period of the Agent service. Without that condition, records from an earlier period when Agent terminated abnormally appear as "running".
Manual run, stop, disable
EXEC msdb.dbo.sp_start_job @job_name = N'Nightly purge';
EXEC msdb.dbo.sp_stop_job @job_name = N'Nightly purge';
EXEC msdb.dbo.sp_update_job @job_name = N'Nightly purge', @enabled = 0;
WARNING
sp_stop_jobrolls back the transaction of the running step.sp_delete_jobdeletes the job and its history. It is safer to disable with@enabled = 0than to delete.