How to wait for a certain period of time in Perl on Linux
I want a Perl script to check a certain PID every couple of minutes and then kill the process. How do I wait those couple of minutes? Thanks.
sleep (n); where n is the number of seconds you want to sleep.
If you want a Perl program to execute at a set time or time interval, then you might want to consider crontab or another scheduler.
If you want perform a wait from within the Perl script, you have a few easily deployable options.
- sleep($n) system call where $n is a numeric value for seconds
- usleep($n) system call where $n is a numeric value for microseconds
Time::HiRes provides a number of functions, some of which override the system calls. Some of the functions include: sleep(), usleep(), nanosleep(),alarm(), ualarm()
Unlike the system call to usleep(), the one packaged with Time::HiRes allows for sleeping more than a second.
use Time::HiRes qw( usleep ualarm gettimeofday tv_interval nanosleep clock_gettime clock_getres clock_nanosleep clock stat );
You'll most likely want to fork your process so that your main program can continue working while that one process is in sleeping in the background.
sleep(120); # sleep for 120 seconds
For delays of finer granularity than one second, you could use usleep from the Time::HiRes module. You may also use Perl's four-argument version of select() leaving the first three arguments undefined:
select(undef, undef, undef, 0.25); # sleep for 250 milliseconds
You're looking for sleep($numSeconds);
So to wait 2 minutes, you would execute sleep(120);
or you could try usleep(microseconds) if a whole second is too long. sleep(0) simply yields to the OS, (discarding what time your process has left on the scheduler). Note that all these functions you ask for the minimum amount of time you want to sleep. The time may be slightly longer on a heavily loaded system.
sleep and usleep are C functions, although Perl, python etc. have functions which call the underling C ones. usleep man page, BSD version, (others are available, try Google)