问题
I have a stored procedure in oracle (which schedules a one-time job to run another procedure, if this is relevant). The job calls another stored procedure which runs for a few minutes, and performs inserts updates and deletes and also uses loops. Now while the long procedure is running, if there is another call for it to run, is it possible to prevent them from executing simultaneously? And even better, to make the second one execute once the previous one has finished, like queue them?
回答1:
To prevent two stored procedures to run at the same time, you could use DBMS_LOCK to get an exclusive lock (or just try to update the same row in a given table).
回答2:
For your purpose the procedure DBMS_LOCK.ALLOCATE_UNIQUE was designed.
Assign some unique lockname
string and call the procedure at the beginning of the critical sequence in your procedure. You will get lockhandle
as an output.
Then call DBMS_LOCK.REQUEST
to start the unique processing
DBMS_LOCK.ALLOCATE_UNIQUE( v_lockname, v_lockhandle);
v_res := DBMS_LOCK.REQUEST( lockhandle=>v_lockhandle, release_on_commit => TRUE);
At the end you must release the handle to be able to process the next run
v_res := DBMS_LOCK.RELEASE (v_lockhandle);
A good practice is to release it also in the EXCEPTION section to be not blocked after the failure.
Please check the possible options in the documentation such as for release_on_commit
and adjust it for your need.
Some care should be taken with the return parameters of the REQUEST
and RELEASE
procedures.
来源:https://stackoverflow.com/questions/62390999/how-to-queue-up-calls-to-stored-procedures-in-oracle