File Coverage

blib/lib/App/Base/Script/OnlyOne.pm
Criterion Covered Total %
statement 18 18 100.0
branch n/a
condition n/a
subroutine 6 6 100.0
pod n/a
total 24 24 100.0


line stmt bran cond sub pod time code
1             package App::Base::Script::OnlyOne;
2 2     2   41192 use strict;
  2         4  
  2         56  
3 2     2   6 use warnings;
  2         4  
  2         54  
4 2     2   8 use Moose::Role;
  2         4  
  2         14  
5              
6 2     2   7664 use Path::Tiny;
  2         2  
  2         98  
7 2     2   816 use File::Flock::Tiny;
  2         1592  
  2         238  
8              
9             our $VERSION = '0.07'; ## VERSION
10              
11             =head1 NAME
12              
13             App::Base::Script::OnlyOne - do not allow more than one instance running
14              
15             =head1 SYNOPSIS
16              
17             use Moose;
18             extends 'App::Base::Script';
19             with 'App::Base::Script::OnlyOne';
20              
21             =head1 DESCRIPTION
22              
23             With this role your script will refuse to start if another copy of the script
24             is running already (or if it is deadlocked or entered an infinite loop because
25             of programming error). After start it tries to lock pid file, and if this is
26             not possible, it dies.
27              
28             =cut
29              
30             around script_run => sub {
31             my $orig = shift;
32             my $self = shift;
33              
34             my $class = ref $self;
35             my $piddir = $ENV{APP_BASE_DAEMON_PIDDIR} || '/var/run';
36             my $pidfile = path($piddir)->child("$class.pid");
37             my $lock = File::Flock::Tiny->write_pid("$pidfile");
38             die "Couldn't lock pid file, probably $class is already running" unless $lock;
39              
40             return $self->$orig(@_);
41             };
42              
43 2     2   8 no Moose::Role;
  2         2  
  2         10  
44             1;
45              
46             __END__