1. 程式人生 > >php原生定時擴充套件的使用(轉載)

php原生定時擴充套件的使用(轉載)

<?php
   
  class  Timer{
    //靜態陣列儲存定時任務;
    protected   static  $task=[];
    //間隔時間;
    protected   static  $time=[];
    //開啟服務
    public  static  function  run(){
            if($time){
            	self::$time=$time;
            }
            self::installHandler();
            pcntl_alarm(1);
    }
    //註冊訊號處理函式;
    public  static  function installHandler(){
    	    pcntl_alarm(SIGALRM,['Timer','signalHandler']);
    }
    //訊號處理函式;
    public  function   signalHandler(){
    	self::task();
    	pcntl_alarm(self::$time);
    }
    //執行回撥函式;
    public   static  function   task(){
             if(empty(self::$task)){
                return "";
             }
        foreach(self::$task as $time=>$arr){
             //遍歷每一個
        	 foreach($arr as $k=>$job){
                     $func=$job['func'];
                     $parm=$job['parm'];
                     $inter=$job['inter'];
                     $persist=$job['persist'];
        	 }
        	 if($current==$time){
                //呼叫回撥函式,傳遞引數;
                call_user_func_array($func, $parm);
                //刪除任務
                unset(self::$task[$time][$k]);
        	 }
        	 if($persist){
                //持久化
                self::$task[$inter+$current]=$job;
        	 }
        }
        public  static   function  add($inter,$func,$parm=[],$persist){
                if(empty($inter)){
                   return ;
                }
                $time=time()+$inter;
            //寫入定時任務;
            self::$task[$time][]=['func'=>$func,'parm'=>$parm,'inter'=>$inter,'persist'=>$persist];
        }

        public  function  dell(){
        	  self::$task=[];
        }
    }
}