use Mutex; my $mutex = Mutex->new( path => $0 ); # choose $0 or tmp path my $mutex = Mutex->new( path => "/tmp/db.lock" ); # The script terminates after some time if a previous # instance is still running with a held lock. exit unless $mutex->timedwait( 5 ); # seconds # Has exclusive lock at this point. Due to using flock, # the lock is released no matter how the process dies, # even if omitting $mutex->unlock. # Do DB insert here. $mutex->unlock; # Do other things, optionally. ...