<?php
namespace KIF\Core;

use KIF\Cli\SingleProcess;

abstract class AbstractDaemon extends Controller {
	
	public function run() {
		$action = $this->action;
		$this->$action();
	}
	
	/**
	 * 
	 * 要完成的业务逻辑,由子类实现
	 */
	abstract protected function doSomething();
	
	/**
	 * 
	 * 脚本存活时间,可由子类重写
	 * @var int
	 */
	protected $aliveTime = 7200;// 2小时
	
	
	/**
	 * 
	 * Enter description here ...
	 * @var KIF\Cli\SingleProcess
	 */
	private $objSingleProcess;
	
	public function __construct() {
		$processId = realpath(__FILE__) . '-' . get_class($this);
		
		$timeout = 2 * $this->aliveTime;// 允许外部脚本kill当前脚本的时间,设置为存活时间的2倍。确保存活时间内,脚本不会被意外杀死。
		$this->objSingleProcess = new SingleProcess($processId, $timeout, true);
		
	}
	
	/**
	 *
	 * 判断脚本是否还能存活
	 * @return Boolean
	 */
	protected function isAlive() {
		static $time_init = null;
		if (is_null($time_init)) {
			$time_init = time();
		}
	
		$time_now = time();
	
	    if ($time_now - $time_init >= $this->aliveTime) {//超过脚本的生存时间
	        return false;
	    }
	
	    return true;
	}
	
	
	protected function doDefault() {
		if ($this->objSingleProcess->isRun()) {
		    echo "已经有进程在跑了\r\n";
		    exit();
		}
		$this->objSingleProcess->run();
		
		do {
			if (!$this->isAlive()) {
	    		break;
	    	}
	    	
	    	$this->doSomething();
	    	
	    	
			
			usleep(1000000);
			echo "休息...\r\n";
		} while ( true );
		
		$this->objSingleProcess->complete();
		echo "done\r\n";
		exit ();
	}
	
}