From af8d5ba00c2e37528afd778c35021748ac63434b Mon Sep 17 00:00:00 2001 From: franck cuny Date: Wed, 14 Apr 2010 10:38:48 +0200 Subject: basic worker --- lib/presque/worker.pm | 79 +++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 74 insertions(+), 5 deletions(-) (limited to 'lib/presque/worker.pm') diff --git a/lib/presque/worker.pm b/lib/presque/worker.pm index 9df647b..6e43c52 100644 --- a/lib/presque/worker.pm +++ b/lib/presque/worker.pm @@ -1,23 +1,88 @@ package presque::worker; -use strict; -use warnings; +use Moose; our $VERSION = '0.01'; +use AnyEvent; +use AnyEvent::HTTP; + +use Carp; +use JSON; +use Try::Tiny; + +has base_uri => ( is => 'ro', isa => 'Str', required => 1 ); +has queue => ( is => 'ro', isa => 'Str', required => 1 ); +has interval => ( is => 'ro', isa => 'Int', lazy => 1, default => 5 ); + +sub BUILD { + my ( $self, $args ) = @_; + my ( $get, $timer ); + + my $uri = $self->base_uri; + my $queue = $self->queue; + my $queue_uri = $uri . '/q/' . $queue; + + if ( !$self->meta->find_method_by_name('work') ) { + Carp::confess "method work is missing"; + } + + $get = sub { + http_get $queue_uri, sub { + my ( $body, $hdr ) = @_; + return if ( !$body || $hdr->{Status} != 200 ); + my $content = JSON::decode_json($body); + + try { + $self->work($content); + } + catch { + $self->fail($content, $_) if $self->meta->find_method_by_name('fail'); + }; + $timer = AnyEvent->timer( after => $self->interval, cb => $get ); + }; + }; + $get->(); + return $self; +} + 1; __END__ =head1 NAME -presque::worker - +presque::worker - a presque worker =head1 SYNOPSIS - use presque::worker; + package myworker; + use Moose; + extends 'presque::worker'; + + sub work { + my ($self, $job) = @_; + ... + } + + sub fail { + my ($self, $job, $error) = @_; + ... + } =head1 DESCRIPTION -presque::worker is +presque::worker - Worker for the C message queue system + +=head1 METHODS + +=head2 work ($job_description) + +Worker must implement the B method. The only argument of this method is a hashref +containing the job. + +=head2 fail ($job_description, $error_reason) + +Worker may implement the B method. This method have two arguments: the job description +and the reason of the failure. =head1 AUTHOR @@ -27,6 +92,10 @@ franck cuny Efranck@lumberjaph.netE =head1 LICENSE +Copyright 2010 by Linkfluence + +L + This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. -- cgit 1.4.1