Chaggster
Chaggster

Reputation: 2511

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.

Upvotes: 26

Views: 103509

Answers (5)

Eugene Yarmash
Eugene Yarmash

Reputation: 149776

Use sleep():

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

Upvotes: 9

RC.
RC.

Reputation: 28207

You're looking for sleep($numSeconds);

So to wait 2 minutes, you would execute sleep(120);

perldoc -f sleep

Upvotes: 4

MJB
MJB

Reputation: 7686

sleep (n); where n is the number of seconds you want to sleep.

Upvotes: 31

vol7ron
vol7ron

Reputation: 42109

Crontab


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.

Perl


If you want perform a wait from within the Perl script, you have a few easily deployable options.

System Calls

  1. sleep($n) system call where $n is a numeric value for seconds
  2. usleep($n) system call where $n is a numeric value for microseconds

Perl Modules

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 );

Suggestion

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.

Upvotes: 12

Chris Huang-Leaver
Chris Huang-Leaver

Reputation: 6089

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)

Upvotes: 1

Related Questions