GithubHelp home page GithubHelp logo

phptimer's Introduction

timer

php定时器,参考了workerman源码,由于workerman源码太过复杂, 故而抽取了一些出来,重新整理出来,实现一个单进程(守护进程)的定时器。

原理

  1. 利用pcntl,守护进程化
  2. 利用stream_select的超时机制,来实现sleep,如果有event扩展的话,优先使用event扩展
  3. 定时器是时间堆的方式实现,利用php的spl的优先队列

使用方式

1.安装

composer require mrtwenty/timer

2.编写index.php

<?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();
  1. 在cli环境上执行:
php index.php

phptimer's People

Contributors

mrtwenty-china avatar mrtwenty avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.