English 中文(简体)
与多个屏蔽监视器环绕的 Perl 事件环绕?
原标题:perl event loop with multiple blocking watchers?

我想弄清楚Perl事件循环的情况?

目前我的节目是这样做的:

    while(my $event = wait_for_event()){
        handle_event($event);
        try_to_do_something();
    }

等待事件被屏蔽 。

我想弄清楚我是否可以使用EV, 或AnyEvent(AE), 或其他东西来增加另一个活动监视器。

例如,我想每两秒钟可以调用 try_to_do_ something (), 但目前却被卡在事件循环中 。

此外,我还想补充一些与该方案的互动形式,可能通过插座(另一个观察者)进行。

谢谢 谢谢

最佳回答

也许你是想做这种事?

use AnyEvent;
use AnyEvent::Filesys::Notify;

sub try_to_do_something { say "every two seconds" }
sub handle_event { say $_->path." ".$_->type for @_ }

my $n = AnyEvent::Filesys::Notify->new(
    dirs => [ /tmp ],
    interval => 0.5,
    filter => sub { 1 },
    cb => sub { handle_event(@_) },
);
my $w = AE::timer 0, 2, sub {try_to_do_something};

AnyEvent->condvar->recv;

这个带“任何夜”和“任何夜”的片段: 文件 : 文件 : 通知只是一种方法。 基本上它几乎总是同样的方式, 不论框架如何 : 用回调设置您的监视器, 并输入您的“ mainloop ” 。

问题回答

事件系统的想法不是写线性代码,阻止某个特定事件的等待,而是设置处理器,以便在事件发生时做什么,然后等待任何这些事件发生。事件框架一般会在事件发生时发送给这些事件处理器。接下来的诀窍是设置处理器,然后等待它。

EV 和 AnyEvent 都会支持这类事情。 另外, 需要查看的还有 < a href="https://metacpan.org/module/POE" rel="noreferr"\\code>\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

总的想法在其中任何一种情况下都大致相同,但我将在IO::Async 中举一个例子,因为我最清楚这一点,主要是因为我写了它。

use IO::Async::Loop;
use IO::Async::Timer::Periodic;

my $loop = IO::Async::Loop->new;

$loop->add( IO::Async::Timer::Periodic->new(
    interval => 2,
    on_tick => &try_to_do_something
)->start );

# Perhaps here you d add your socket watcher, using an
# IO::Async::Handle or ::Stream or something else

$loop->run;

$loop- & gt; add 方法将一个通知对象安装到循环中, 在此情况下, 它是一个周期计时器, 每两秒运行指定函数。 在程序底部, 主的 $loop- gt; run 方法会在适当的时候发送给事件处理者 。





相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签