php定時器 phptimer

phptimer是本人蔘考workerman的源碼, 從裏面分離出來的一個定時器,在linux上,守護進程化,可以添加多個定時器。

使用方式很簡單:

1、composer安裝

composer require mrtwenty/timer

2、編寫測試代碼,如果是win,可以在命令行上查看,linux上會定時寫入時間到/tmp/test.txt上的

<?php
require __DIR__ . '/vendor/autoload.php';
use timer\Daemon;

$timer = Daemon::runAll();

//測試執行 timer類
function microtime_float()
{
    list($usec, $sec) = explode(" ", microtime());
    return bcadd($usec, $sec, 3);
}

$timer->add(0.5, function () {

    if (Daemon::getOS() === OS_TYPE_WIN) {
        echo microtime_float() . "\n";
    } else {
        file_put_contents("/tmp/test.txt", microtime_float() . "\n", FILE_APPEND);
    }
});

$timer->add(1, function () {

    if (Daemon::getOS() === OS_TYPE_WIN) {
        echo microtime_float() . "once \n";
    } else {
        file_put_contents("/tmp/test.txt", microtime_float() . "once \n", FILE_APPEND);
    }
}, false);

$timer->loop();

3、在命令行上執行

 php index.php

win上效果如圖所示: 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章