Add a +Restart plugin that restarts the class on SIGHUP (configurable)
Jonathan Rockway [Tue, 12 May 2009 00:14:51 +0000 (19:14 -0500)]
example/LongRunning.pm [new file with mode: 0644]
lib/MooseX/Runnable/Invocation/Plugin/Restart.pm [new file with mode: 0644]

diff --git a/example/LongRunning.pm b/example/LongRunning.pm
new file mode 100644 (file)
index 0000000..df8856c
--- /dev/null
@@ -0,0 +1,16 @@
+package LongRunning;
+use Moose;
+use 5.010;
+
+with 'MooseX::Runnable';
+
+# I use this to test the +Restart plugins
+
+sub run {
+    say "[$$] App is starting";
+    while(1){
+        sleep 86400;
+    }
+}
+
+1;
diff --git a/lib/MooseX/Runnable/Invocation/Plugin/Restart.pm b/lib/MooseX/Runnable/Invocation/Plugin/Restart.pm
new file mode 100644 (file)
index 0000000..cc49382
--- /dev/null
@@ -0,0 +1,52 @@
+package MooseX::Runnable::Invocation::Plugin::Restart;
+use Moose::Role;
+use MooseX::Types::Moose qw(Str);
+use AnyEvent;
+use namespace::autoclean;
+
+with 'MooseX::Runnable::Invocation::Plugin::Restart::Base';
+
+has 'completion_condvar' => (
+    is       => 'ro',
+    isa      => 'AnyEvent::CondVar',
+    required => 1,
+    default  => sub { AnyEvent->condvar },
+);
+
+has 'kill_signal' => (
+    is       => 'ro',
+    isa      => Str,
+    required => 1,
+    default  => sub { 'INT' },
+);
+
+has 'restart_signal' => (
+    is       => 'ro',
+    isa      => Str,
+    required => 1,
+    default  => sub { 'HUP' },
+);
+
+after '_restart_parent_setup' => sub {
+    my $self = shift;
+
+    my ($kw, $rw);
+    $kw = AnyEvent->signal( signal => $self->kill_signal, cb => sub {
+        $self->kill_child;
+        undef $kw;
+        $self->completion_condvar->send(0); # parent exit code
+    });
+
+    $rw = AnyEvent->signal( signal => $self->restart_signal, cb => sub {
+        $rw = $rw; # closes over $rw and prevents it from being GC'd
+        $self->restart;
+    });
+};
+
+sub run_parent_loop {
+    my $self = shift;
+    print {*STDERR} "Control pid is $$\n";
+    return $self->completion_condvar->wait;
+}
+
+1;