TABLE OF CONTENTS

NAME

Mojo::Reactor::Poll - poll 实现的事件反应堆

SYNOPSIS

use Mojo::Reactor::Poll;

# Watch if handle becomes readable or writable
my $reactor = Mojo::Reactor::Poll->new;
$reactor->io($first => sub {
  my ($reactor, $writable) = @_;
  say $writable ? 'First handle is writable' : 'First handle is readable';
});

# Change to watching only if handle becomes writable
$reactor->watch($first, 0, 1);

# Turn file descriptor into handle and watch if it becomes readable
my $second = IO::Handle->new_from_fd($fd, 'r');
$reactor->io($second => sub {
  my ($reactor, $writable) = @_;
  say $writable ? 'Second handle is writable' : 'Second handle is readable';
})->watch($second, 1, 0);

# Add a timer
$reactor->timer(15 => sub {
  my $reactor = shift;
  $reactor->remove($first);
  $reactor->remove($second);
  say 'Timeout!';
});

# Start reactor if necessary
$reactor->start unless $reactor->is_running;

DESCRIPTION

Mojo::Reactor::Poll 是一个低级别的基于 IO::Poll 实现的事件反应堆.

EVENTS

Mojo::Reactor::Poll 继承全部的 Mojo::Reactor 的事件.

METHODS

Mojo::Reactor::Poll 继承全部的 Mojo::Reactor 的方法, 并实现了下面这些.

again

$reactor->again($id);

重启 timer. 注意, 此方法需要一个活动的 timer.

io

$reactor = $reactor->io($handle => sub {...});

监控 I/O 句柄事件, 当事件是可读或者可写的时候, 调用回调.

# Callback will be invoked twice if handle becomes readable and writable
$reactor->io($handle => sub {
  my ($reactor, $writable) = @_;
  say $writable ? 'Handle is writable' : 'Handle is readable';
});

is_running

my $bool = $reactor->is_running;

检查反应堆是否运行.

one_tick

$reactor->one_tick;

运行反应堆直到有事件发行, 如果没有事件监控会在次运行反应堆. 注意这方法可以递归回反应堆, 所以你需要小心.

# Don't block longer than 0.5 seconds
my $id = $reactor->timer(0.5 => sub {});
$reactor->one_tick;
$reactor->remove($id);

recurring

my $id = $reactor->recurring(0.25 => sub {...});

创建一个新的循环的 timer, 在指定的间隔时间调用回调.

remove

my $bool = $reactor->remove($handle);
my $bool = $reactor->remove($id);

删除句柄或者 timer.

reset

$reactor->reset;

删除全部的句柄或者 timer.

start

$reactor->start;

开始监控 I/O 和 timer 事件, 这会阻塞直到 "stop"" in " 被调用. 注意有些反应堆是会在没事件的时候自动停止的.

# Start reactor only if it is not running already
$reactor->start unless $reactor->is_running;

stop

$reactor->stop;

停止监控 I/O 和 timer 事件.

timer

my $id = $reactor->timer(0.5 => sub {...});

创建一个新的 timer. 在指定的时间后调用回调.

watch

$reactor = $reactor->watch($handle, $readable, $writable);

对于 I/O 事件上创建监控, 指定 true 和 false 的值. 注意这需要一个活动的 I/O 监控者.

# Watch only for readable events
$reactor->watch($handle, 1, 0);

# Watch only for writable events
$reactor->watch($handle, 0, 1);

# Watch for readable and writable events
$reactor->watch($handle, 1, 1);

# Pause watching for events
$reactor->watch($handle, 0, 0);

SEE ALSO

Mojolicious, Mojolicious::Guides, http://mojolicio.us.