Mojolicious-Plugin-DirectoryQueue

 view release on metacpan or  search on metacpan

lib/Mojolicious/Plugin/DirectoryQueue.pm  view on Meta::CPAN

package Mojolicious::Plugin::DirectoryQueue;

use Mojo::Base 'Mojolicious::Plugin';
use Mojo::JSON qw(decode_json encode_json);
use Directory::Queue;
use POSIX qw(chown);

our $VERSION = '0.01';


sub register {
    my ($plugin, $app, $args) = @_;

    $args->{path}  ||= '/tmp/DirQueue';
    my $dirq = Directory::Queue->new( path => $args->{path} );

    my $config = $app->config;
    if ( $config->{hypnotoad} and $config->{hypnotoad}->{user} ) {
        my ($uid,$gid) = ( getpwnam($config->{hypnotoad}->{user}) )[2,3];
        chown $uid, $gid, $args->{path};
    }

    $app->helper(
        enqueue => sub {
            my ($self, $args) = @_;
            $dirq->add(encode_json($args));
        },
    );

    $app->helper(
        dequeue => sub {
            for (my $name = $dirq->first(); $name; $name = $dirq->next()) {
               next unless $dirq->lock($name);
               my $data = $dirq->get($name);
               $dirq->remove($name);
               return decode_json($data) if $data;
            }
            return;
        },
    );

    $app->helper(
        show => sub {
            my @all;
            for (my $name = $dirq->first(); $name; $name = $dirq->next()) {
               next unless $dirq->lock($name);
               my $data = $dirq->get($name);
               push @all, decode_json($data) if $data;
               $dirq->unlock($name);
            }
            return \@all;
        },
    );

    $app->helper(
        count => sub {
            return $dirq->count();
        },
    );
    $app->helper(
        purge => sub {
            my $self = shift;
            return $dirq->purge(@_);
        },
    );
};

1;
__END__

=pod 

=encoding utf-8

=head1 NAME

Mojolicious::Plugin::DirectoryQueue - Mojolicious 应用使用的内部队列服务, 基本本地文件系统的队列系统 , 为方便做任务应用使用. 

=head1 SYNOPSIS



( run in 0.686 second using v1.01-cache-2.11-cpan-71847e10f99 )