How can I tell Perl to run some code every 20 seconds?
相关问题
- $ENV{$variable} in perl
- Is it possible to pass command-line arguments to @
- Redirecting STDOUT and STDERR to a file, except fo
- Change first key of multi-dimensional Hash in perl
- How do I get a filehandle from the command line?
相关文章
- Running a perl script on windows without extension
- Comparing speed of non-matching regexp
- Can NOT List directory including space using Perl
- Extracting columns from text file using Perl one-l
- Lazy (ungreedy) matching multiple groups using reg
- How do I tell DBD::mysql where mysql.sock is?
- What is a good way to deploy a Perl application?
- Speeding up Selenium Webdriver
Go with ..
Set up a SIGALRM handler, and send yourself a signal every 20 seconds with
alarm
(see perldoc -f alarm):This will experience drift over time, as each signal may be delayed by up to a second; if this is important, set up a cron job instead. Additionally, even more drift will happen if your other code takes upwards of 20 seconds to run, as only one timer can be counting at once. You could get around this by spawning off threads, but at this point, I would have already gone back to a simple cron solution.
Choosing the proper solution is dependent on what sort of task you need to execute periodically, which you did not specify.
It is better to use some event library. There are a couple of choices:
IO::Async::Timer::Periodic
AnyEvent::DateTime::Cron
EV::timer
etc.
While the
sleep
function will work for some uses, if you're trying to do "every 20 seconds, forever", then you're better off using an external utility likecron
.In addition to the possible issue of drift already mentioned, if your
sleep
script exits (expectedly or otherwise), then it's not going to run again at the next 20 second mark.@Blrfl is correct, and I feel sheepish. That said, it's easy enough to overcome.
You could also take a hybrid approach of putting a limited count sleep loop in the script and using cron to run it every X minutes, covering the case of script death. Anything more frequent than 20 seconds, I would definitely take that approach.