Skip to content

Instantly share code, notes, and snippets.

@kanonji
Created October 3, 2011 08:19
Show Gist options
  • Save kanonji/1258690 to your computer and use it in GitHub Desktop.
Save kanonji/1258690 to your computer and use it in GitHub Desktop.
Gearmanの練習
#!/usr/bin/perl
use strict;
use warnings;
use Gearman::Client;
#use Gearman::Task;
use Storable qw/freeze/;
use Getopt::Long qw/GetOptions/;
my %opts = ();
GetOptions(\%opts, qw/m=s@ job=s async=i/);
my $args = freeze($opts{m});
my $client = Gearman::Client->new;
$client->job_servers(qw/localhost/);
my $result;
if ( exists $opts{async} and 1 == $opts{async} ) {
print "---dispatch_background-----------------------\n";
$result = $client->dispatch_background($opts{job}, \$args, {});
print $result;
print "\n";
} else {
print "---do_task-----------------------------------\n";
$result = $client->do_task($opts{job}, \$args, {});
print $$result;
print "\n";
}
#!/usr/bin/perl
use strict;
use warnings;
use Gearman::Worker;
use Storable qw/thaw/;
use Smart::Comments;
my $worker = Gearman::Worker->new;
$worker->job_servers(qw/localhost/);
$worker->register_function(
sample_job_a => sub {
my ( $self ) = @_;
return job_a( $self->arg );
}
);
$worker->register_function(
sample_job_b => sub {
my ( $self ) = @_;
return job_b( $self->arg );
}
);
sub job_a {
my ( $arg ) = @_;
$arg = thaw($arg);
print "--job_a-------------------\n";
### $arg;
if ( 'ARRAY' eq ref $arg ) {
sub { print "job_a : $_\n";sleep 3;}->() for @$arg;
} else {
print $arg;
print "\n";
}
return 1;
}
sub job_b {
my ( $arg ) = @_;
$arg = thaw($arg);
print "--job_b-------------------\n";
### $arg;
if ( 'ARRAY' eq ref $arg ) {
sub { print "job_b : $_\n";sleep 5}->() for @$arg;
} else {
print $arg;
print "\n";
}
return 1;
}
$worker->work while 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment