Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl
- package Pending;
- use Mojo::Base -base;
- use Mojo::Exception;
- use Mojo::IOLoop;
- use Linux::Inotify2;
- __PACKAGE__->attr(ioloop => sub {Mojo::IOLoop->singleton});
- has [qw/dir on_new on_delete/];
- sub new {
- my $class = shift;
- my $self = $class->SUPER::new(@_);
- Mojo::Exception->throw("dir not provided") unless $self->dir;
- $self->{notify} = new Linux::Inotify2;
- $self->{notify}->watch($self->dir, IN_CREATE | IN_MOVED_TO | IN_MOVED_FROM | IN_DELETE, sub {$self->_notify(@_)});
- #open my $fh, "+<&", $self->{notify}->fileno or die $!;
- #open my $fh, "+<=&", $self->{notify}->fileno or die $!;
- open $self->{watching}, "<&=", $self->{notify}->fileno or die $!;
- $self->ioloop->reactor->io($self->{watching} => sub {$self->{notify}->poll});
- $self->ioloop->reactor->watch($self->{watching}, 1, 0);
- return $self;
- }
- sub _notify {
- my ($self, $event) = @_;
- print "Evented\n";
- if (($event->IN_MOVED_FROM || $event->IN_DELETE) && ref $self->on_delete()) {
- print "File deleted\n";
- &{$self->on_delete()}($self, $event);
- }
- elsif (($event->IN_CREATE || $event->IN_MOVE_TO) && ref $self->on_new()) {
- print "File added\n";
- &{$self->on_new()}($self, $event);
- }
- }
- sub _dir {
- my ($self, @path) = @_;
- return File::Spec->catdir($self->dir, @path);
- }
- sub _file {
- my ($self, @path) = @_;
- return File::Spec->catfile($self->dir, @path);
- }
- package main;
- use Mojo::IOLoop;
- mkdir './pending' unless -e './pending';
- my $loop = Mojo::IOLoop->singleton();
- my $pending = new Pending(
- dir => './pending',
- on_delete => sub {
- print "Deleted!\n"
- },
- on_new => sub {
- print "NEW!\n"
- }
- );
- $loop->start();
- print "$!\n";
- print $^F . "\n";
Add Comment
Please, Sign In to add comment