Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to put a timer on script execution, and exit if too long

Status
Not open for further replies.

webscripter

Programmer
Jul 29, 2002
266
US
Hi everyone,

I would like to know if it's possible to create a timer for my scripts. If it times out I want it to exit.

Thanks
Pat
ideas@microwebber.com
 
Generally this is handled in two ways that I have seen. There can be some process that is outside your script that calls your script then kills it after some time period. Or, within your script, identify any processes that you execute that would be prone to long execution and your script times them and kills them if it needs to.

[blue]"Well, once again my friend, we find that science is a two headed beast. One head is nice, it gives us aspirin and other modern conveniences,...but the other head of science is BAD! Oh, beware the other head of science, Arthur; it bites!!" - The Tick[/blue]
 
$SIG{'ALRM'} = sub { die "Timeout exceeded, exiting\n"; };
alarm($your_timeout);

You could use this trick in an eval block to timeout just a part of the program and handle the timeout gracefully.
 
Just a side note, you want to put a second eval block around the first one to null out the alarm in the event that the script encounters a race condition.

___________________________________
[morse]--... ...--[/morse], Eric.
 
Straight out of the cookbook:
Code:
eval{
     local $SIG{ALARM} = sub { die "time threshold reached"};
     alarm 10; #how long in seconds do you want it to wait
     eval{
          #timed operation here
          };
          alarm 0;   #cancel alarm
    }
    alarm 0; #prevent race condition
die if $@ && $@ !~ /alarm clock restart/; #reraise

___________________________________
[morse]--... ...--[/morse], Eric.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top