Line # Revision Author
1 3 ahitrov@rambler.ru package PidFile;
2
3 use strict;
4 use warnings 'all';
5
6 use Contenido::DateTime;
7 use PidFile::Database;
8 use PidFile::DatabaseCompat;
9 use PidFile::File;
10
11
12 my $singleton;
13
14 sub new {
15 $singleton ||= _new(@_);
16 }
17
18 #XXX: compat.
19 sub start {
20 __PACKAGE__->new(@_);
21 }
22
23 sub _new {
24 my ($class, $storage, %opts) = @_;
25
26 select((select(STDERR), $|=1)[0]);
27 select((select(STDOUT), $|=1)[0]);
28
29 my $now = time;
30
31 my $self = {
32 lclass => 'PidFile::'.(ref $storage ? 'Database'.($opts{compat} ? 'Compat' : '') : 'File'),
33 started => $now,
34 verbose => $opts{verbose},
35 };
36
37 $opts{host} = (`hostname`=~/(.*)/)[0];
38 if ($opts{host_only} && $opts{host_only} ne $opts{host}) {
39 print "This script executes only at $opts{host_only}, exit\n" if $opts{verbose};
40 exit;
41 }
42
43 printf "\nPID $$ started at ".localtime($now)."\n" if $self->{verbose};
44 $self->{lock} = $self->{lclass}->new($storage, %opts);
45 $self->{lock}->block($now);
46
47 bless $self, $class;
48 }
49
50 sub DESTROY {
51 my $self = shift;
52
53 my $now = time;
54 my $delay = $self->{lock}->release($now);
55 print "PID $$ finished at ".localtime($now)." (elapsed ".($now - $self->{started})." seconds".($delay ? " in execute and $delay seconds in sleep" : "").")\n" if $self->{verbose};
56 }
57
58 sub END {
59 undef $singleton;
60 }
61
62 1;