分享

PHP定时器

 小马哥技术屋 2017-08-06
PHP定时器Timer类
    内容见附件 windows下的定时是用ping所以不是很准确
需要系统有curl的支持 linux可以 yum install curl 即可
windows 把附件的curl.exe 放到代码中的cmd里面的目录E:\YS\JAVA\curl\curl.exe即可
  1. /**
  2.  *  定时器
  3.  */
  4. class Timer {
  5.     const LOG_PRE = 'base/lib/timer/';
  6.     const SHELL_DIR = 'basetimer/';
  7.     private $tips;
  8.     /**
  9.      *  初始化
  10.      */
  11.     public function __construct() {
  12.         
  13.     }
  14.     /**
  15.      *  根据 时间 和 url 延时请求 url
  16.      *  return 0|ok 1|err
  17.      */
  18.     public function addTimer($time, $url) {
  19.         $time = floor(floatval($time));
  20.         $nowTime = $this->microTime();
  21.         $type = $this->isWin();
  22.         $logTimer = [];
  23.         $logTimer[] = '开始添加定时任务addTimer:'.$nowTime;
  24.         $logTimer[] = 'time='.$time;
  25.         $logTimer[] = 'url='.$url;
  26.         $fileName = $this->fileName($url);
  27.         $file = $this->shellDir().$fileName;
  28.         $filePostFix = $type ? '.bat' : '.sh';
  29.         $file = $file.$filePostFix;
  30.         if ($type) {
  31.             $file = $this->cmdPathReplace($file);
  32.         }
  33.         $logTimer[] = 'file='.$file;
  34.         $logTimer[] = 'sys type='.($type ? 'cmdStr' : 'shellStr');
  35.         // shell
  36.         $shellStr = <<<shellStr
  37. #!/bin/sh
  38. # $nowTime
  39. #time $time
  40. #url $url
  41. echo `date +"%Y-%m-%d %H:%M:%S"`
  42. sleep $time
  43. echo `date +"%Y-%m-%d %H:%M:%S"`
  44. curl $url
  45. # delete file
  46. if [ -f $file ]; then
  47.     rm -f $file
  48. fi
  49. shellStr;
  50.         $shellStr = str_replace("\r", '', $shellStr);
  51.         $logTimer[] = 'shellStr=';
  52.         $logTimer[] = $shellStr;
  53.         // cmd
  54.         $cmdStr = <<<cmdStr
  55. rem $nowTime
  56. rem time $time
  57. rem url $url
  58. @echo off
  59. echo %Date% %Time%
  60. ping -n $time 127.0.0.1>nul
  61. echo %Date% %Time%
  62. E:\YS\JAVA\curl\curl.exe $url
  63. rem delete file
  64. if exist $file del $file
  65. exit
  66. cmdStr;
  67.         $logTimer[] = 'cmdStr=';
  68.         $logTimer[] = $cmdStr;
  69.         $logTimer[] = 'file_put_contents='.file_put_contents($file, $type ? $cmdStr : $shellStr);
  70.         $this->log($logTimer);
  71.         // 执行shell
  72.         if ($type) {
  73.             $this->runCmdFile($file, $fileName);
  74.         } else {
  75.             $this->runShellFile($file, $fileName);
  76.         }
  77.         return 0;
  78.     }
  79.     /**
  80.      *  根据 文件 执行 shell
  81.      */
  82.     private function runShellFile($file, $fileName) {
  83.         $logFile = $this->shellLogDir().$fileName.'.log';
  84.         pclose(popen("sh $file >> $logFile &", "r"));
  85.     }
  86.     /**
  87.      *  根据 文件 执行 cmd
  88.      */
  89.     private function runCmdFile($file, $fileName) {
  90.         $logFile = $this->shellLogDir().$fileName.'.log';
  91.         pclose(popen("start /b $file >> $logFile", "r"));
  92.     }
  93.     /**
  94.      *  cmd path replace
  95.      */
  96.     private function cmdPathReplace($path) {
  97.         $path = str_replace('/', '\\', $path);
  98.         return $path;
  99.     }
  100.     /**
  101.      *  判断 是否是 windows
  102.      *  return ture|是 false|不是
  103.      */
  104.     private function isWin() {
  105.         $name = php_uname();
  106.         if (strtolower(substr($name, 0, 6)) == 'window') {
  107.             return true;
  108.         }
  109.         return false;
  110.     }
  111.     /**
  112.      *  日志记录
  113.      */
  114.     private function log($con, $type = '') {
  115.         $folder = self::LOG_PRE.$type.'/';
  116.         $file = './FileData/'.$folder;
  117.         $time = time();
  118.         $file = $file.'/'.date('Ym', $time).'/'.date('Ymd', $time).'.log';
  119.         // 创建文件
  120.         if (!$this->file($file)) {
  121.             return false;
  122.         }
  123.         // 追加写入
  124.         if (file_put_contents($file, var_export($con, true), FILE_APPEND | LOCK_EX) === false) {
  125.             $this->tips = '写入文件失败!';
  126.             return false;
  127.         }
  128.         return true;
  129.     }
  130.     /**
  131.      *  获取shell 保存的绝对目录 以 / 结尾
  132.      */
  133.     private function shellDir() {
  134.         $path = './FileData/';
  135.         $path = $path.self::SHELL_DIR.'shelldir/';
  136.         $file = 'readme.md';
  137.         if ($this->file($path.$file)) {
  138.             $path = dirname(realpath($path.$file)).'/';
  139.         }
  140.         return $path;
  141.     }
  142.     /**
  143.      *  获取 shell log 保存的绝对目录 以 / 结尾
  144.      */
  145.     private function shellLogDir() {
  146.         $time = time();
  147.         $path = './FileData/';
  148.         $path = $path.self::SHELL_DIR.'shelldir/'.'runshelllog/'.date('Ym/', $time);
  149.         $file = 'readme.md';
  150.         if ($this->file($path.$file)) {
  151.             $path = dirname(realpath($path.$file)).'/';
  152.         }
  153.         return $path;
  154.     }
  155.     /**
  156.      *  生成一个新的文件名 用来记录即将要执行的shell
  157.      */
  158.     private function fileName($key = '') {
  159.         $key = md5('md5'.$key);
  160.         // 其实这里创建一张表 来维护这些文件名最好 但我就不
  161.         list($h, $t) = explode(' ', microtime());
  162.         $date = date('YmdHis', $t);
  163.         $time = $date.substr($h, 2);
  164.         $max = 10000000;
  165.         $rand = rand(1, $max);
  166.         $num = $max + floor($rand);
  167.         $name = $time.'ms'.$num.'r'.$key;
  168.         $name = strtolower($name);
  169.         return $name;
  170.     }
  171.     /**
  172.      *  判断文件是否存在 ,不存在创建
  173.      */
  174.     public function file($file) {
  175.         $result = true;
  176.         if (file_exists($file)) {
  177.             return true;
  178.         }
  179.         // 创建目录
  180.         if (!$this->mkDir(dirname($file))) {
  181.             return false;
  182.         }
  183.         // 创建文件
  184.         $fp = fopen($file, "x+");
  185.         if (!$fp) {
  186.             $result = false;
  187.             $this->tips = $file.' 文件创建失败!';
  188.         }
  189.         fclose($fp);
  190.         return $result;
  191.     }
  192.     /**
  193.      *  创建文件夹
  194.      */
  195.     public function mkDir($path) {
  196.         if (is_dir($path)) {
  197.             return true;
  198.         }
  199.         if (!is_dir(dirname($path))) {
  200.             if (!$this->mkDir(dirname($path))) {
  201.                 return false;
  202.             }
  203.             return $this->mkDir($path);
  204.         }
  205.         if (!mkdir($path)) {
  206.             $this->tips = $path.' 目录创建失败!';
  207.             return false;
  208.         }
  209.         return true;
  210.     }
  211.     /**
  212.      *  获取 当前时间 毫秒级
  213.      */
  214.     public function microTime() {
  215.         list($h, $t) = explode(' ', microtime());
  216.         $date = date('Y-m-d H:i:s', $t);
  217.         $time = $date.'.'.substr($h, 2);
  218.         return $time;
  219.     }
  220. }
用法如下
  1. //使用
  2. $timer = new Timer();
  3. $timer->addTimer(10, 'www.thinkphp.cn');

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多