<?php
/**
* 腳本鎖
*
* 主要用于防止 crontab 腳本重復執行
* @author eason
* @date 2011-11-22
*/
class ScriptLock {
private $configs;
static private $orderno;//用于區分腳本
function __construct() {
$this->orderno = time();
$this->configs = require(dirname(__FILE__) . '/Config/ScriptLock.inc.php');
}
/*
* 設置pid文件生成路徑 -- 一般不會用到
*/
public function setDir($dir){
$this->configs['lock_file'] = $dir;
}
/*
* Script lock file 創建及檢查
*/
public function create($file) {
$file_name = md5($file);
$lock_dir = $this->configs['lock_file'];
$lock_file = $lock_dir.'/'.$file_name.'.pid';
if(!file_exists($lock_file) ){
if(!$this->mkdirs($lock_dir)){
die("Failed to create file directory! ".$lock_dir);
}
$fp = fopen($lock_file, 'w') or die('Lock file can not write! '.$lock_file);
@fwrite($fp,'ok');
@fclose($fp);
$this->write_log($file. "\t\tscript run begin");
}else{
$this->write_log($file. "\t\tscript had runed");
die("Script had runed! ");
}
}
/*
* Script lock file 刪除
*/
public function delete($file){
$file_name = md5($file);
$lock_dir = $this->configs['lock_file'];
$lock_file = $lock_dir.'/'.$file_name.'.pid';
if(file_exists($lock_file) ){
if (!unlink($lock_file)){
die("Lock file delete error! ".$lock_file);
}else{
$this->write_log($file. "\t\tscript run end");
die("Lock file had deleted! ");
}
}
}
/**
* 創建一個/多個目錄
*/
public function mkdirs($dir){
if(!is_dir($dir)){
if(!$this->mkdirs(dirname($dir))){
return false;
}
if(!mkdir($dir,0777)){
return false;
}
}
return true;
}
function write_log($msg) {
$lock_dir = $this->configs['lock_file'];
$log_dir = $lock_dir."/log";
if(!$this->mkdirs($log_dir)){
die("Failed to create file directory! ".$log_dir);
}
$log_file = $log_dir."/".date('Ymd').".txt";
$fp = fopen($log_file, 'a');
@fwrite($fp, date('Y-m-d H:i:s', time()) . "\t" . $this->orderno . "\t" . $msg . "\r\n");
@fclose($fp);
}
}
?>
没有合适的资源?快使用搜索试试~ 我知道了~
php 防止脚本重复执行
共3个文件
php:3个
5星 · 超过95%的资源 需积分: 50 23 下载量 184 浏览量
2011-11-22
19:20:10
上传
评论
收藏 2KB RAR 举报
温馨提示
ScriptLock 类来统一控制脚本,防止脚本重复执行 Config 配置的是 {lock}.pid文件的路径和log的路径 其中要说明下的是$orderno 是执行该脚本时的一个表示 2011-11-22 19:05:00 1321959900 /var/www/script/crontab/dk/event/online_time/count.php script run begin 2011-11-22 19:07:14 1321960034 /var/www/script/crontab/dk/event/online_time/count.php script had runed 2011-11-22 19:07:53 1321960073 /var/www/script/crontab/dk/event/online_time/count.php script had runed 2011-11-22 19:12:19 1321959900 /var/www/script/crontab/dk/event/online_time/count.php script run end 1321959900 这个说明是同一个脚本的执行
资源推荐
资源详情
资源评论
收起资源包目录
ScriptLock.rar (3个子文件)
ScriptLock
index.php 199B
ScriptLock.class.php 2KB
Config
ScriptLock.inc.php 82B
共 3 条
- 1
资源评论
- xingky2012-12-16不错的, 10.8.2 可以用
- 小小芳1532014-04-22有帮助的, 各取所需
- alenalenalen0002012-11-19已验证可用
zyx164823178
- 粉丝: 1
- 资源: 7
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功