![]() |
YAP 7.1.0
|
alarm(+ Seconds,+ Callable,+ OldAlarm) More...
alarm(+ Seconds,+ Callable,+ OldAlarm)
Arranges for YAP to be interrupted in Seconds seconds, or in [ Seconds| MicroSeconds] When interrupted, YAP will execute Callable and then return to the previous execution If Seconds is 0
, no new alarm is scheduled In any event, any previously set alarm is canceled
The variable OldAlarm unifies with the number of seconds remaining until any previously scheduled alarm was due to be delivered, or with 0
if there was no previously scheduled alarm
Note that execution of Callable will wait if YAP is executing built-in predicates, such as Input/Output operations
The next example shows how alarm/3 can be used to implement a simple clock:
The clock, ticker
, writes a dot and then checks the flag tick
to see whether it can continue ticking If so, it calls itself again Note that there is no guarantee that the each dot corresponds a second: for instance, if the YAP is waiting for user input, ticker
will wait until the user types the entry in
The next example shows how alarm/3 can be used to guarantee that a certain procedure does not take longer than a certain amount of time:
In this case after 10
seconds our loop
is interrupted, ball
is thrown, and the handler writes Quota exhausted
Execution then continues from the handler
Note that in this case loop/0
always executes until the alarm is sent Often, the code you are executing succeeds or fails before the alarm is actually delivered In this case, you probably want to disable the alarm when you leave the procedure The next procedure does exactly so:
The procedure once_with_alarm/3
has three arguments: the Time to wait before the alarm is sent; the Goal to execute; and the goal DoOnAlarm to execute if the alarm is sent It uses catch/3 to handle the case the alarm
is sent Then it starts the alarm, calls the goal Goal, and disables the alarm on success or failure