DBAtlas · Database operations atlas

Create, run manually, disable and drop a scheduler job

OracleScheduler

Command

-- 1) Create disabled, set attributes, then enable:
BEGIN
  DBMS_SCHEDULER.CREATE_JOB(
    job_name        => 'CUSTOMER_APP.NIGHTLY_STATS',
    job_type        => 'PLSQL_BLOCK',
    job_action      => q'[BEGIN DBMS_STATS.GATHER_SCHEMA_STATS(ownname => 'CUSTOMER_APP', options => 'GATHER STALE'); END;]',
    start_date      => SYSTIMESTAMP,
    repeat_interval => 'FREQ=DAILY; BYHOUR=2; BYMINUTE=30; BYSECOND=0',
    enabled         => FALSE,
    auto_drop       => FALSE,
    comments        => 'Nightly stale statistics gathering');
  DBMS_SCHEDULER.SET_ATTRIBUTE('CUSTOMER_APP.NIGHTLY_STATS', 'max_run_duration', INTERVAL '2' HOUR);
  DBMS_SCHEDULER.SET_ATTRIBUTE('CUSTOMER_APP.NIGHTLY_STATS', 'logging_level', DBMS_SCHEDULER.LOGGING_FULL);
  DBMS_SCHEDULER.ENABLE('CUSTOMER_APP.NIGHTLY_STATS');
END;
/

-- 2) Validate the calendar expression (next run time):
SET SERVEROUTPUT ON
DECLARE
  l_next TIMESTAMP WITH TIME ZONE;
BEGIN
  DBMS_SCHEDULER.EVALUATE_CALENDAR_STRING(
    calendar_string   => 'FREQ=DAILY; BYHOUR=2; BYMINUTE=30; BYSECOND=0',
    start_date        => SYSTIMESTAMP,
    return_date_after => SYSTIMESTAMP,
    next_run_date     => l_next);
  DBMS_OUTPUT.PUT_LINE('Next run: ' || l_next);
END;
/

-- 3) Run now in the background (does not affect the schedule):
EXEC DBMS_SCHEDULER.RUN_JOB('CUSTOMER_APP.NIGHTLY_STATS', use_current_session => FALSE);

-- 4) Status:
SELECT owner, job_name, enabled, state, run_count, failure_count,
       last_start_date, next_run_date
FROM   dba_scheduler_jobs WHERE owner = 'CUSTOMER_APP';

-- 5) Stop (if running) / disable / drop:
-- EXEC DBMS_SCHEDULER.STOP_JOB('CUSTOMER_APP.NIGHTLY_STATS', force => FALSE);
EXEC DBMS_SCHEDULER.DISABLE('CUSTOMER_APP.NIGHTLY_STATS', force => TRUE);
EXEC DBMS_SCHEDULER.DROP_JOB('CUSTOMER_APP.NIGHTLY_STATS', force => TRUE);

What it does

Defines a scheduled PL/SQL job with DBMS_SCHEDULER; sets max_run_duration (raises an event when exceeded) and a detailed logging level, validates the calendar expression in advance, and allows a manual run without disturbing the schedule.

When to use it

To run recurring database work such as maintenance, ETL and cleanup inside the database instead of cron, with RAC/Data Guard awareness.

Caution

No extra license. The time zone of start_date matters: SYSTIMESTAMP uses the database server's TZ; use an explicit region (e.g. 'Europe/Istanbul') to avoid drift at DST changes. If JOB_QUEUE_PROCESSES=0 no job runs. DISABLE with force=>TRUE does not stop a running instance, it only prevents future runs; use STOP_JOB to interrupt it. Creating a job in another schema requires CREATE ANY JOB.

Open in DBAtlas →

Related