| 网站首页 | 文章中心 | 电子书下载 | 矢量图库 | 视频教程 | 素材下载 | 程序代码下载 | JS代码 | 论坛 | 
常用软件类:
|杀毒安全 |联络聊天 |网络软件 |多媒体类 |系统工具 |图形图像 |系统工具 |应用软件 |行业软件
开发设计类:
|动画制作 |图像处理 |3D设计 |操作系统 |站长学院 |网络相关 |WEB设计 |数据库类 |程序开发
PHP构建一个简易监视引擎
作者:佚名    文章来源:网络    点击数:    更新时间:2006-11-19
 



  三. 保证排它性

  你可能经常想实现:一个脚本在任何时刻仅运行一个实例。为了保护脚本,这是特别重要的,因为在后台运行容易导致偶然情况下调用多个实例。

  保证这种排它性的标准技术是,通过使用flock()来让脚本锁定一个特定的文件(经常是一个加锁文件,并且被排它式使用)。如果锁定失败,该脚本应该输出一个错误并退出。下面是一个示例:

$fp=fopen("/tmp/.lockfile","a");
if(!$fp || !flock($fp, LOCK_EX | LOCK_NB)) {
 fputs(STDERR, "Failed to acquire lock\n");
 exit;
}
/*成功锁定以安全地执行工作*/


  注意,有关锁机制的讨论涉及较多内容,在此不多加解释。

 

四. 构建监视服务

  在这一节中,我们将使用PHP来编写一个基本的监视引擎。因为你不会事先知道怎样改变,所以你应该使它的实现既灵活又具可能性。
该记录程序应该能够支持任意的服务检查(例如,HTTP和FTP服务)并且能够以任意方式(通过电子邮件,输出到一个日志文件,等等)记录事件。你当然想让它以一个守护程序方式运行;所以,你应该请求它输出其完整的当前状态。

  一个服务需要实现下列抽象类:

abstract class ServiceCheck {
 const FAILURE = 0;
 const SUCCESS = 1;
 protected $timeout = 30;
 protected $next_attempt;
 protected $current_status = ServiceCheck::SUCCESS;
 protected $previous_status = ServiceCheck::SUCCESS;
 protected $frequency = 30;
 protected $description;
 protected $consecutive_failures = 0;
 protected $status_time;
 protected $failure_time;
 protected $loggers = array();
 abstract public function __construct($params);
 public function __call($name, $args)
 {
  if(isset($this->$name)) {
   return $this->$name;
  }
 }
 public function set_next_attempt()
 {
  $this->next_attempt = time() + $this->frequency;
 }
 public abstract function run();
 public function post_run($status)
 {
  if($status !== $this->current_status) {
   $this->previous_status = $this->current_status;
  }
  if($status === self::FAILURE) {
   if( $this->current_status === self::FAILURE ) {
    $this->consecutive_failures++;
   }
   else {
    $this->failure_time = time();
   }
  }
  else {
   $this->consecutive_failures = 0;
  }
  $this->status_time = time();
  $this->current_status = $status;
  $this->log_service_event();
 }
 public function log_current_status()
 {
  foreach($this->loggers as $logger) {
   $logger->log_current_status($this);
  }
 }
 private function log_service_event()
 {
  foreach($this->loggers as $logger) {
   $logger->log_service_event($this);
  }
 }
 public function register_logger(ServiceLogger $logger)
 {
  $this->loggers[] = $logger;
 }
}


  上面的__call()重载方法提供对一个ServiceCheck对象的参数的只读存取操作:

上一页  [1] [2] [3] [4] [5] 下一页


相关文章