# Dude, Where's My Job?

There are times where a process we've created can step on its own toes if multiple instances of it run at the same time; data corruption being a common outcome when concurrency is not a design consideration.

For some, DBMS_SCHEDULER jobs are used as a convenient solution because:

1. Monitoring can be performed using Oracle's own internal tooling such as the %\_SCHEDULER_RUNNING_JOBS and %SHEDULER_JOB_LOG views.
2. When a job is running, subsequent **scheduled** executions are blocked until the current job finishes providing a degree of concurrency control.
3. **Ad-hoc** job executions can be triggered when needed and, when *USE_CURRENT_SESSION* is FALSE, will be prevented with Oracle raising error ORA-27478 if the job is already running.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p>The USE_CURRENT_SESSION parameter in the call to DBMS_SCHEDULER.RUN_JOB, when set to FALSE, means the job is triggered asynchronously and execution returns immediately to the calling session. When set to TRUE (the default), it tells Oracle to execute the job using the current session and wait for it to complete.</p></div>
</div>

However, when a job is called <u>using the current session</u>, you might expect it to still have all those same benefits listed above. First thing you will notice is its distinct absence from the the %\_SCHEDULER_RUNNING_JOBS view, leaving you scratching your head uttering the words of this blog's title.

Let's create a job that does nothing but sleep for 5 minutes to simulate a "significant" body of work being processed.

```sql
BEGIN
   SYS.DBMS_SCHEDULER.CREATE_JOB(JOB_NAME        => 'JOB_A',
                                 JOB_TYPE        => 'PLSQL_BLOCK',
                                 JOB_ACTION      => 'BEGIN DBMS_SESSION.SLEEP(SECONDS => 300); END;',
                                 START_DATE      => TO_DATE(NULL),
                                 REPEAT_INTERVAL => '',
                                 END_DATE        => TO_DATE(NULL),
                                 JOB_CLASS       => 'DEFAULT_JOB_CLASS',
                                 ENABLED         => FALSE,
                                 AUTO_DROP       => FALSE,
                                 COMMENTS        => 'Test Job');
END;
/
```

If we run the job and set USE_CURRENT_SESSION to TRUE in one session.

```sql
BEGIN
   DBMS_SCHEDULER.RUN_JOB(JOB_NAME => 'JOB_A', USE_CURRENT_SESSION => TRUE);
END;
/
```

Then in another session we query the view for running jobs:

```sql
SELECT J.*
FROM   DBA_SCHEDULER_RUNNING_JOBS J;
```

JOB_A is not returned but this query. However, if we repeat this but with USE_CURRENT_SESSION set to FALSE, then we do see JOB_A returned by the view.

The reason for this is that when a job is run within the current session, Oracle, perhaps surprisingly to some, doesn't pass the job to the DBMS_SCHEDULER coordinator to offload it as a slave process, it simply extracts the job's action and executes that. The %\_SCHEDULER_RUNNING_JOBS view only reports jobs controlled by the coordinator.

Imagine you have a job that can be triggered by users, perhaps in an APEX application, and the same job can also be invoked by numerous back-end processes as part of other business workflows, having the scheduler coordinator manage any conflicts is very convenient.

As mentioned earlier, an error is raised when someone or something tries to run the job if it is already running and this can be trapped and handled. This does require the USE_CURRENT_SESSION parameter to be set to FALSE, if set to TRUE, the database will *always* execute the job action **without** ORA-27478 being raised or any job queuing occurring.

The moral of the story is that using jobs to control concurrency is convenient but certainly not fool proof and if you want to ensure only one session can work a process at any one time, you should use a different approach.

To that end, DBMS_LOCK is a great option for such a requirement. Assuming you have a package where you store all your utility functions/procedures, you can use the following as wrapper APIs to lock a process while a session is running it.

```sql
FUNCTION LOCK_PROCESS(P_PROCESS_NAME IN VARCHAR2) RETURN VARCHAR2 IS
   V_RESULT     INTEGER;
   V_LOCKHANDLE VARCHAR2(128);
BEGIN
   -- Create/get a named lock unique to this process
   DBMS_LOCK.ALLOCATE_UNIQUE(LOCKNAME => P_PROCESS_NAME, LOCKHANDLE => V_LOCKHANDLE);

   -- Attempt to acquire an exclusive lock.
   -- timeout => 0 means don't wait if another instance owns it.
   -- don't let commits release the lock
   V_RESULT := DBMS_LOCK.REQUEST(LOCKHANDLE        => V_LOCKHANDLE,
                                 LOCKMODE          => DBMS_LOCK.X_MODE,
                                 TIMEOUT           => 0,
                                 RELEASE_ON_COMMIT => FALSE);

   IF V_RESULT <> 0 THEN
      RAISE_APPLICATION_ERROR(-20111, 'Process ' || P_PROCESS_NAME ||
                                                   ' is already locked by another session.');
   END IF;

   RETURN V_LOCKHANDLE;

END LOCK_PROCESS;

----------------------------------------------------------------
PROCEDURE RELEASE_PROCESS_LOCK(P_LOCKHANDLE IN VARCHAR2) IS
   V_RESULT INTEGER;
BEGIN

   V_RESULT := DBMS_LOCK.RELEASE(P_LOCKHANDLE);

END RELEASE_PROCESS_LOCK;
```

LOCK_PROCESS can be called when your process starts, and RELEASE_PROCESS_LOCK can be called when your process terminates (remember to add it to any EXCEPTION handlers) to release the exclusive lock.

If another instance of your process calls this API to attempt to obtain a lock while the first is running, the error will be raised. Just be sure to provide a unique P_PROCESS_NAME for each distinct process you want to lock to be run as a single thread.

Yes, it does require injecting these calls into your processes and isn't as convenient for monitoring as using DBMS_SCHEDULER but it is far more robust a solution and is also self-documenting to future developers that the process is designed to run one instance at a time.

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text"><p>Other approaches seen in the wild are opening cursors with FOR UPDATE on a dummy table that will block concurrent execution of the process. However, one unexpected commit, explicit or implicit, in the code that follows the opening of this cursor and this lock is released allowing the other process to proceed.</p></div>
</div>

So, be mindful of how you invoke the DBMS_SCHEDULER.RUN_JOB if you intend to rely on the %\_SCHEDULER_RUNNING_JOBS to monitor its execution or on the scheduler's coordinator to prevent concurrent executions.
