さて、すっかりMoose厨となりつつある私ですが、この度デーモンスクリプトを書くことになりましたのでMooseでこれをするのは何がいいかなと考えていたわけです。したらなんでもありますな、CPANは。MooseX::Daemonizeですよ、奥さん。
考え方としては、スクリプトの書式をコントロールするオブジェクトをまず作ります。
package MyDaemon;
use Moose;
with 'MooseX::Daemonize';
コマンドラインから受け取るオプション等はこのオブジェクトの属性として指定します。
has 'option1' => (
is => 'rw',
isa => 'Str',
required => 1
);
has 'option2' => (
is => 'rw',
isa => 'Bool',
default => 1,
);
このような指定をすると、--option1=hoge --option2 のように指定できるようになります。
after 'start' => sub {
my $self = shift;
return unless $self->is_daemon;
# デーモンプロセスで行う処理をここへ
};
以上。あとはPODに書いてある通りのスクリプトをを用意して・・・
my $daemon = My::Daemon->new_with_options();
my ($command) = @{$daemon->extra_argv}
defined $command || die "No command specified";
$daemon->start if $command eq 'start';
$daemon->status if $command eq 'status';
$daemon->restart if $command eq 'restart';
$daemon->stop if $command eq 'stop';
warn($daemon->status_message);
exit($daemon->exit_code);
で、このスクリプトを、こんな感じで動かすだけ。start/stop/status/restartが最初から装備されているのがセクシーすぎる。
./script.pl --option1=hoge --option2 start
コメント