遅まきながらJobキューを使いたくて、あれこれかじっています。perlだとTheSchwartzがメジャーな雰囲気だったので試してみました。
準備
まずjobキュー用のデータベースを準備します。上記ページには説明がありませんが、スキーマもCPANにあがっています。ここではtheschwartzという名前のデータベースをdb_userユーザから使っています。
$ wget http://search.cpan.org/src/BRADFITZ/TheSchwartz-1.07/doc/schema.sql
$ mysqladmin -u root create theschwartz
$ mysql -u root theschwartz < schema.sql
$ mysql -u root
> grant all on theschwartz.* to db_user@localhost identified by 'db_pass';
ジョブの追加処理
まずキューにジョブを追加します。ジョブの追加はTheSchwartz本体でも出来ますが、不要なオブジェクトのロードが走らないのでTheSchwartz::Simpleを使うのが良いようです。
#!/usr/bin/perl
use strict;
use warnings;
use Perl6::Say;
use DBI;
use TheSchwartz::Simple;
my $dbh = DBI->connect('dbi:mysql:theschwartz', 'db_user', 'db_pass');
my $client = TheSchwartz::Simple->new($dbh);
my $id = $client->insert('SampleWorker', {'data' => @ARGV ? $ARGV[0] : 10});
say "job $id is inserted";
ジョブを実行する処理
ジョブの実行はTheSchwartz本体で行います。TheSchwartz::Workerのサブクラスでジョブの実行処理を記述し、そのクラスを$TheSchwartz->can_doで指定します。後は$TheSchwartz->workでひたすらキューに入ったジョブを実行し続けてくれます。下記コードでは実行した事をログに残すだけのジョブを処理しています。
#!/usr/bin/perl
package SampleWorker;
use strict;
use warnings;
use base qw(TheSchwartz::Worker);
use Perl6::Say;
use IO::File;
sub work {
my ($class, $job) = @_;
say "working";
my $file = IO::File->new;
$file->open('work.txt', 'a') or die $!;
$file->print($job->arg->{'data'} . " is done\n");
$file->close();
$job->completed();
}
package main;
use strict;
use warnings;
use TheSchwartz;
my $worker = TheSchwartz->new(
databases => [{
dsn => 'dbi:mysql:theschwartz',
user => 'db_user',
pass => 'db_pass'
}]);
$worker->can_do('SampleWorker');
$worker->work();
割とシンプルに使えていいですね。TheSchwartzってネーミングがよく解りませんけども。
後でQ4Mと使い比べてみようと思います。