Worker.class.php 2.55 KB
<?php

class Util_Gearman_Worker extends Util_Gearman_Abstract {
	
	/**
	 * 私有状态
	 *
	 * @var Mixed
	 */
	private $_status;
	
	/**
	 * 构造函数
	 */
	public function __construct() {
		parent::__construct('worker');
	}
	
	/**
	 * 添加(登记)一个调用函数
	 *
	 * @param String $function_name
	 * @param String $function
	 * @param Mixed $context
	 * @param Integer $timeout
	 * @return Util_Gearman_Worker
	 */
	public function addFunction($function_name, $function, &$context = null, $timeout = 0) {
		$this->_status = $this->gearmanObj->addFunction($function_name, $function, $context, $timeout);
		return $this;
	}
	/**
	 * 获取设置参数
	 *
	 * @return String
	 */
	public function getOptions() {
		return $this->geramanObj->options();
	}
	
	/**
	 * 注册一个方法
	 *
	 * @param String $function_name
	 * @param Integer $timeout
	 * @return Util_Gearman_Worker
	 */
	public function register($function_name, $timeout = 0) {
		$this->_status = $this->geramanObj->register($function_name, $timeout);
		return $this;
	}
	
	/**
	 * 移除选项
	 *
	 * @param Integer $options
	 * @return Util_Gearman_Worker
	 */
	public function removeOptions($options) {
		$this->_status = $this->gearmanObj->removeOptions($options);
		return $this;
	}
	
	/**
	 * 注销一个已经注册的方法
	 *
	 * @param String $function_name
	 * @return Util_Gearman_Worker
	 */
	public function unregister($function_name) {
		$this->_status = $this->gearmanObj->unregister($function_name);
		return $this;
	}
	
	/**
	 * 注销所有注册的方法
	 *
	 * @return Util_Gearman_Worker
	 */
	public function unregisterAll() {
		$this->_status = $this->gearmanObj->unregisterAll();
		return $this;
	}
	
	/**
	 * 等待获取任务
	 *
	 * @return bool
	 */
	public function wait() {
		return $this->gearmanObj->wait();
	}
	
	/**
	 * 运行等待获取任务
	 *
	 * @return String
	 */
	public function runWait() {
		while (@$this->gearmanObj->work() || $this->gearmanObj->returnCode() == GEARMAN_IO_WAIT || $this->gearmanObj->returnCode() == GEARMAN_NO_JOBS) {
			if ($this->gearmanObj->returnCode() == GEARMAN_SUCCESS)
				continue;
			
		# Waiting for next job...\n
			if (!@$this->gearmanObj->wait()) {
				if ($this->gearmanObj->returnCode() == GEARMAN_NO_ACTIVE_FDS) {
					# We are not connected to any servers, so wait a bit before 
					# trying to reconnect. 
					sleep(5);
					continue;
				}
				break;
			}
		}
		return "Worker Error: " . $this->gearmanObj->error() . "\n";
	}
	
	/**
	 * 获取一个任务并执行
	 */
	public function work() {
		while ($this->gearmanObj->work());
	}

}