Wednesday 14 September 2011

Can I start a timer inside PLSQL

Question:

I have a requirement to have a timer start after an insert into a table. After a short time, I would initiate another activity. How can I program that requirement in PL/SQL?

Answer:

Pio, it's not hard to start a timer in your session. Download the Timer or Stopwatch Object Type Definition here, which allows you to create an object type-based "stopwatch" so you can start and stop a timer from within PL/SQL. Here is an example of using such a timer:
DECLARE
c_iterations CONSTANT PLS_INTEGER := 100;

stopwatch_tmr tmr_t :=
NEW tmr_t ('Run My Test', c_iterations);
BEGIN
stopwatch_tmr.go;
FOR indx IN 1 .. c_iterations
LOOP
run_my_test;
END LOOP;
stopwatch_tmr.stop;
END;
/

The tricky part to your question has to do with being able to detect that a certain amount of time has passed, which then triggers a new activity. PL/SQL executes in a single thread. If you want to "kick off" new activities (and then continue on with your current activity), you essentially need to send a message to another session, which then gets moving on your request.
You can use either Oracle's Advanced Queuing facility or the simpler DBMS_PIPE package to implement messaging between sessions.
You might also consider DBMS_JOB or Oracle 10g's new DBMS_SCHEDULER. If you simply want to start a new activity in, say, 30 seconds, you could submit a job with a start time of 30 seconds in the future, and no repeat execution of the job. The job manager would then wake up, check for the job and kick it off, independently of the session from which the job was scheduled.

No comments:

Post a Comment