Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running only one Perl script instance by cron

Tags:

I need to run Perl script by cron periodically (~every 3-5 minutes). I want to ensure that only one Perl script instance will be running in a time, so next cycle won't start until the previous one is finished. Could/Should that be achieved by some built-in functionality of cron, Perl or I need to handle it at script level?

I am quite new to Perl and cron, so help and general recommendations are appreciated.

like image 724
Gennady Shumakher Avatar asked Feb 09 '10 22:02

Gennady Shumakher


2 Answers

I have always had good luck using File::NFSLock to get an exclusive lock on the script itself.

use Fcntl qw(LOCK_EX LOCK_NB); use File::NFSLock;  # Try to get an exclusive lock on myself. my $lock = File::NFSLock->new($0, LOCK_EX|LOCK_NB); die "$0 is already running!\n" unless $lock; 

This is sort of the same as the other lock file suggestions, except I don't have to do anything except attempt to get the lock.

like image 196
oylenshpeegul Avatar answered Dec 22 '22 01:12

oylenshpeegul


The Sys::RunAlone module does what you want very nicely. Just add

  use Sys::RunAlone; 

near the top of your code.

like image 21
Jonathan A. Marshall Avatar answered Dec 22 '22 01:12

Jonathan A. Marshall