PHP code example of workbunny / event-loop

1. Go to this page and download the library: Download workbunny/event-loop library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

workbunny / event-loop example snippets


use WorkBunny\EventLoop\Loop;
use WorkBunny\EventLoop\Drivers\NativeLoop;
use WorkBunny\EventLoop\Drivers\EventLoop;
use WorkBunny\EventLoop\Drivers\EvLoop;
use WorkBunny\EventLoop\Drivers\SwowLoop;

// 创建PHP原生loop
$loop = Loop::create(NativeLoop::class);
// 创建ext-event loop
$loop = Loop::create(EventLoop::class);
// 创建ext-ev loop
$loop = Loop::create(EvLoop::class);
// 创建swow loop
$loop = Loop::create(SwowLoop::class);

use WorkBunny\EventLoop\Loop;
// 注册
loop::register(YourLoopClass::class);
// 创建
$yourLoop = Loop::create(YourLoopClass::class);

/**
 * @Future [delay=0.0, repeat=false]
 *  在下一个周期执行,执行一次即自动销毁
 */
$loop->addTimer(0.0, false, function (){ echo 'timer'; }); // loop->run()后立即输出字符串

/**
 * @ReFuture [delay=0.0, repeat=0.0]
 *  在每一个周期执行,不会自动销毁
 */
$id = $loop->addTimer(0.0, 0.0, function () use(&$loop, &$id) {
    // 此方法可以实现自我销毁
    $loop->delTimer($id);
});

/**
 * @DelayReFuture [delay>0.0, repeat=0.0]
 *  延迟delay秒后每一个周期执行,不会自动销毁
 */
$id = $loop->addTimer(1.0, 0.0, function () use(&$loop, &$id) {
    // 此方法可以实现自我销毁
    $loop->delTimer($id);
});

/**
 * @Delayer [delay>0.0, repeat=false]
 *  延迟delay秒后执行,执行一次即自动销毁
 */
$loop->addTimer(2.0, false, function (){ echo 'timer'; }); // loop->run() 2秒后输出字符串

/**
 * @Timer [delay=0.0, repeat>0.0]
 *  在下一个周期开始每间隔repeat秒执行,不会自动销毁
 */
$id = $loop->addTimer(0.1, 0.1, function () use(&$loop, &$id) {
    // 此方法可以实现自我销毁
    $loop->delTimer($id);
});

/**
 * @DelayTimer [delay>0.0, repeat>0.0]
 *  延迟delay秒后每间隔repeat秒执行,不会自动销毁
 */
$id = $loop->addTimer(0.2, 0.1, function () use(&$loop, &$id) {
    // 此方法可以实现自我销毁
    $loop->delTimer($id);
});

// 创建
$loop->addReadStream(resource, function (resource $stream) { });
// 注意:EvLoop在这里较为特殊,回调函数的入参为EvIo对象
$loop->addReadStream(resource, function (\EvIo $evio) {
    $evio->stream // resource 资源类型
});
// 移除
$loop->delReadStream(resource);

// 创建
$loop->addWriteStream(resource, function (resource $stream) { });
// 注意:EvLoop在这里较为特殊,回调函数的入参为EvIo对象
$loop->addWriteStream(resource, function (\EvIo $evio) {
    $evio->stream // resource 资源类型
});
// 移除
$loop->delWriteStream(resource);

// 注册
$loop->addSignal(\SIGUSR1, function (){});
// 移除
$loop->delSignal(\SIGUSR1, function (){});

# 该函数后会阻塞
$loop->loop();

# 该行代码不会执行
var_dump('123');

$loop->destroy();

# 该行代码会执行
var_dump('123');