Tuesday, December 25, 2007

Delaying a job by less than a second:

How do we check if new records have been added to a physical file?

There are ways to wait for the latest record to be added, for instance, using end of file delay (OVRDBF with EOFDLY), but this is equivalent to having a delayed job should no record be found, and try to read it again. It is also possible to couple a data queue to a file and send a message to the data queue every time a record is added to the file. This in turn will "wake up" the batch job and make it read the file.
The easiest way to poll a file would be to reposition to the start and read a record every time the end of file is met. But this is not a good solution as jobs continually polling a file in this way will take far too much CPU and slow the system down. Delay must be introduced. The simplest way is to add a delay job (DLYJOB) every time an end of file condition is met. But DLYJOB is not perfect. The minimum time you can delay a job with it is one second. You can delay a job by only a number of seconds, not a fraction of a second.
One second is fine in most cases, but sometimes, you can't afford to wait for one second and you can't afford not to wait. This is where a C function comes in handy. "pthread_delay_np" delays a thread for a number of nanoseconds!
This API is written in C and therefore expects parameters in a specific format.

D timeSpec ds
D seconds 10i 0
D nanoseconds 10i 0

I declared the API as follows:

D delay pr 5i 0 extProc('pthread_delay_np')
d * value

The API expects a pointer to the timespec definition. It also returns a non-zero value if a problem occurred (which is unlikely if you are passing a valid timespec).

A specimen code:

c eval seconds = 0
c eval nanoseconds = 10000000
c eval return = delay(%addr(timeSpec))
c if return <> 0
c callP (e) system('DLYJOB 1')
c endIf

No comments: