Skip to content

Commit aacfd9f

Browse files
committed
reformat code and add comment
1 parent c7526d6 commit aacfd9f

7 files changed

Lines changed: 182 additions & 136 deletions

File tree

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
<?php
2+
/**
3+
* Created by PhpStorm.
4+
* User: Jenner
5+
* Date: 2015/8/6
6+
* Time: 18:55
7+
*/
8+
9+
namespace Jenner\Zebra\Crontab;
10+
11+
use Monolog\Logger;
12+
use Monolog\ErrorHandler;
13+
14+
15+
class AbstractDaemon
16+
{
17+
/**
18+
* cron minssion config
19+
* @var array
20+
*/
21+
protected $crontab_config;
22+
23+
/**
24+
* monolog instance
25+
* @var Logger
26+
*/
27+
protected $logger;
28+
29+
/**
30+
* @param Logger $logger
31+
*/
32+
public function __construct($logger)
33+
{
34+
$this->setLogger($logger);
35+
}
36+
37+
/**
38+
* set logger
39+
* @param Logger $logger
40+
*/
41+
public function setLogger(Logger $logger)
42+
{
43+
$this->logger = $logger;
44+
ErrorHandler::register($logger);
45+
}
46+
47+
/**
48+
* start crontab and loop
49+
*/
50+
public function start()
51+
{
52+
$this->logger->info("crontab start");
53+
$crontab = new Crontab($this->crontab_config, $this->logger);
54+
$timer = new \EvPeriodic(0., 60., null, function ($timer, $revents) use ($crontab) {
55+
$pid = pcntl_fork();
56+
if ($pid > 0) {
57+
return;
58+
} elseif ($pid == 0) {
59+
$crontab->start(time());
60+
exit();
61+
} else {
62+
$this->logger->error("could not fork");
63+
exit();
64+
}
65+
});
66+
67+
$child = new \EvChild(0, false, function ($child, $revents) {
68+
pcntl_waitpid($child->rpid, $status);
69+
$message = "process exit. pid:" . $child->rpid . ". exit code:" . $child->rstatus;
70+
$this->logger->info($message);
71+
});
72+
73+
\Ev::run();
74+
$this->logger->info("crontab exit");
75+
}
76+
}

src/Jenner/Zebra/Crontab/Crontab.php

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -60,9 +60,9 @@ public function start($time)
6060
$this->logger->info("start cmd:" . $mission['cmd']);
6161
$user_name = isset($mission['user_name']) ? $mission['user_name'] : null;
6262
$group_name = isset($mission['group_name']) ? $mission['group_name'] : null;
63-
try{
63+
try {
6464
$manager->fork(new Process([$mission_executor, 'start'], $mission['name']), $user_name, $group_name);
65-
}catch (\Exception $e){
65+
} catch (\Exception $e) {
6666
$this->logger->error($e->getMessage(), $e->getTraceAsString());
6767
}
6868

@@ -95,16 +95,17 @@ protected function getMission()
9595
* 格式化定时任务配置数组
9696
* @return array
9797
*/
98-
protected function formatMission(){
98+
protected function formatMission()
99+
{
99100
$mission_array = [];
100-
foreach($this->mission as $mission_value){
101-
if(is_array($mission_value['time']) && !empty($mission_value['time'])){
102-
foreach($mission_value['time'] as $time){
101+
foreach ($this->mission as $mission_value) {
102+
if (is_array($mission_value['time']) && !empty($mission_value['time'])) {
103+
foreach ($mission_value['time'] as $time) {
103104
$tmp = $mission_value;
104105
$tmp['time'] = $time;
105106
$mission_array[] = $tmp;
106107
}
107-
}else{
108+
} else {
108109
$mission_array[] = $mission_value;
109110
}
110111
}
@@ -116,7 +117,8 @@ protected function formatMission(){
116117
* @param array $mission
117118
* @return mixed
118119
*/
119-
public function addMission(array $mission){
120+
public function addMission(array $mission)
121+
{
120122
return array_merge($this->mission, $mission);
121123
}
122124
}

src/Jenner/Zebra/Crontab/CrontabParse.php

Lines changed: 58 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -9,40 +9,41 @@
99
namespace Jenner\Zebra\Crontab;
1010

1111

12-
/**
13-
* @author: Jan Konieczny <jkonieczny@gmail.com>
14-
* @copyright: Copyright (C) 2009, Jan Konieczny
15-
*
16-
* This is a simple script to parse crontab syntax to get the execution time
17-
*
18-
* Eg.: $timestamp = Crontab::parse('12 * * * 1-5');
19-
*
20-
*
21-
* This program is free software: you can redistribute it and/or modify
22-
* it under the terms of the GNU General Public License as published by
23-
* the Free Software Foundation, either version 3 of the License, or
24-
* (at your option) any later version.
25-
*
26-
* This program is distributed in the hope that it will be useful,
27-
* but WITHOUT ANY WARRANTY; without even the implied warranty of
28-
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29-
* GNU General Public License for more details.
30-
*
31-
* You should have received a copy of the GNU General Public License
32-
* along with this program. If not, see <http://www.gnu.org/licenses/>.
33-
*/
12+
/**
13+
* @author: Jan Konieczny <jkonieczny@gmail.com>
14+
* @copyright: Copyright (C) 2009, Jan Konieczny
15+
*
16+
* This is a simple script to parse crontab syntax to get the execution time
17+
*
18+
* Eg.: $timestamp = Crontab::parse('12 * * * 1-5');
19+
*
20+
*
21+
* This program is free software: you can redistribute it and/or modify
22+
* it under the terms of the GNU General Public License as published by
23+
* the Free Software Foundation, either version 3 of the License, or
24+
* (at your option) any later version.
25+
*
26+
* This program is distributed in the hope that it will be useful,
27+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
28+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29+
* GNU General Public License for more details.
30+
*
31+
* You should have received a copy of the GNU General Public License
32+
* along with this program. If not, see <http://www.gnu.org/licenses/>.
33+
*/
3434
/**
3535
* Provides basic cron syntax parsing functionality
3636
*
3737
* @author: Jan Konieczny <jkonieczny@gmail.com>
3838
* @copyright: Copyright (C) 2009, Jan Konieczny
3939
*/
40-
class CrontabParse {
40+
class CrontabParse
41+
{
4142
/**
4243
* Finds next execution time(stamp) parsin crontab syntax,
4344
* after given starting timestamp (or current time if ommited)
4445
*
45-
* @param string $_cron_string:
46+
* @param string $_cron_string :
4647
*
4748
* 0 1 2 3 4
4849
* * * * * *
@@ -53,40 +54,41 @@ class CrontabParse {
5354
* | | +--------- day of month (1 - 31)
5455
* | +----------- hour (0 - 23)
5556
* +------------- min (0 - 59)
56-
* @param int $_after_timestamp timestamp [default=current timestamp]
57-
* @return int unix timestamp - next execution time will be greater
57+
* @param int $_after_timestamp timestamp [default=current timestamp]
58+
* @return int unix timestamp - next execution time will be greater
5859
* than given timestamp (defaults to the current timestamp)
59-
* @throws \InvalidArgumentException
60+
* @throws \InvalidArgumentException
6061
*/
61-
public static function parse($_cron_string,$_after_timestamp=null)
62+
public static function parse($_cron_string, $_after_timestamp = null)
6263
{
63-
if(!preg_match('/^((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)$/i',trim($_cron_string))){
64-
throw new \InvalidArgumentException("Invalid cron string: ".$_cron_string);
64+
if (!preg_match('/^((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)\s+((\*(\/[0-9]+)?)|[0-9\-\,\/]+)$/i', trim($_cron_string))) {
65+
throw new \InvalidArgumentException("Invalid cron string: " . $_cron_string);
6566
}
66-
if($_after_timestamp && !is_numeric($_after_timestamp)){
67+
if ($_after_timestamp && !is_numeric($_after_timestamp)) {
6768
throw new \InvalidArgumentException("\$_after_timestamp must be a valid unix timestamp ($_after_timestamp given)");
6869
}
69-
$cron = preg_split("/[\s]+/i",trim($_cron_string));
70-
$start = empty($_after_timestamp)?time():$_after_timestamp;
71-
$date = array( 'minutes' =>self::_parseCronNumbers($cron[0],0,59),
72-
'hours' =>self::_parseCronNumbers($cron[1],0,23),
73-
'dom' =>self::_parseCronNumbers($cron[2],1,31),
74-
'month' =>self::_parseCronNumbers($cron[3],1,12),
75-
'dow' =>self::_parseCronNumbers($cron[4],0,6),
70+
$cron = preg_split("/[\s]+/i", trim($_cron_string));
71+
$start = empty($_after_timestamp) ? time() : $_after_timestamp;
72+
$date = array('minutes' => self::_parseCronNumbers($cron[0], 0, 59),
73+
'hours' => self::_parseCronNumbers($cron[1], 0, 23),
74+
'dom' => self::_parseCronNumbers($cron[2], 1, 31),
75+
'month' => self::_parseCronNumbers($cron[3], 1, 12),
76+
'dow' => self::_parseCronNumbers($cron[4], 0, 6),
7677
);
7778
// limited to time()+366 - no need to check more than 1year ahead
78-
for($i=0;$i<=60*60*24*366;$i+=60){
79-
if( in_array(intval(date('j',$start+$i)),$date['dom']) &&
80-
in_array(intval(date('n',$start+$i)),$date['month']) &&
81-
in_array(intval(date('w',$start+$i)),$date['dow']) &&
82-
in_array(intval(date('G',$start+$i)),$date['hours']) &&
83-
in_array(intval(date('i',$start+$i)),$date['minutes'])
84-
){
85-
return $start+$i;
79+
for ($i = 0; $i <= 60 * 60 * 24 * 366; $i += 60) {
80+
if (in_array(intval(date('j', $start + $i)), $date['dom']) &&
81+
in_array(intval(date('n', $start + $i)), $date['month']) &&
82+
in_array(intval(date('w', $start + $i)), $date['dow']) &&
83+
in_array(intval(date('G', $start + $i)), $date['hours']) &&
84+
in_array(intval(date('i', $start + $i)), $date['minutes'])
85+
) {
86+
return $start + $i;
8687
}
8788
}
8889
return null;
8990
}
91+
9092
/**
9193
* get a single cron style notation and parse it into numeric value
9294
*
@@ -95,18 +97,18 @@ public static function parse($_cron_string,$_after_timestamp=null)
9597
* @param int $max maximum possible value
9698
* @return int parsed number
9799
*/
98-
protected static function _parseCronNumbers($s,$min,$max)
100+
protected static function _parseCronNumbers($s, $min, $max)
99101
{
100102
$result = array();
101-
$v = explode(',',$s);
102-
foreach($v as $vv){
103-
$vvv = explode('/',$vv);
104-
$step = empty($vvv[1])?1:$vvv[1];
105-
$vvvv = explode('-',$vvv[0]);
106-
$_min = count($vvvv)==2?$vvvv[0]:($vvv[0]=='*'?$min:$vvv[0]);
107-
$_max = count($vvvv)==2?$vvvv[1]:($vvv[0]=='*'?$max:$vvv[0]);
108-
for($i=$_min;$i<=$_max;$i+=$step){
109-
$result[$i]=intval($i);
103+
$v = explode(',', $s);
104+
foreach ($v as $vv) {
105+
$vvv = explode('/', $vv);
106+
$step = empty($vvv[1]) ? 1 : $vvv[1];
107+
$vvvv = explode('-', $vvv[0]);
108+
$_min = count($vvvv) == 2 ? $vvvv[0] : ($vvv[0] == '*' ? $min : $vvv[0]);
109+
$_max = count($vvvv) == 2 ? $vvvv[1] : ($vvv[0] == '*' ? $max : $vvv[0]);
110+
for ($i = $_min; $i <= $_max; $i += $step) {
111+
$result[$i] = intval($i);
110112
}
111113
}
112114
ksort($result);

src/Jenner/Zebra/Crontab/Daemon.php

Lines changed: 2 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -8,23 +8,12 @@
88

99
namespace Jenner\Zebra\Crontab;
1010

11-
12-
use Monolog\ErrorHandler;
1311
use Monolog\Handler\NullHandler;
1412
use Monolog\Handler\StreamHandler;
1513
use Monolog\Logger;
1614

17-
class Daemon
15+
class Daemon extends AbstractDaemon
1816
{
19-
/**
20-
* @var array
21-
*/
22-
protected $crontab_config;
23-
24-
/**
25-
* @var Logger
26-
*/
27-
protected $logger;
2817

2918
/**
3019
* @param $crontab_config
@@ -33,53 +22,14 @@ class Daemon
3322
public function __construct($crontab_config, $logfile)
3423
{
3524
$this->crontab_config = $crontab_config;
36-
3725
$logger = new Logger("php_crontab");
3826
if (!empty($logfile)) {
3927
$logger->pushHandler(new StreamHandler($logfile));
4028
} else {
4129
$logger->pushHandler(new NullHandler());
4230
}
4331
$this->logger = $logger;
44-
ErrorHandler::register($logger);
45-
}
46-
47-
/**
48-
* 设置monolog对象
49-
* @param Logger $logger
50-
*/
51-
public function setLogger(Logger $logger)
52-
{
53-
$this->logger = $logger;
54-
}
55-
56-
/**
57-
* 开始运行,不退出模式
58-
*/
59-
public function start()
60-
{
61-
$this->logger->info("crontab start");
62-
$crontab = new Crontab($this->crontab_config, $this->logger);
63-
$timer = new \EvPeriodic(0., 60., null, function ($timer, $revents) use ($crontab) {
64-
$pid = pcntl_fork();
65-
if($pid>0){
66-
return;
67-
}elseif($pid==0){
68-
$crontab->start(time());
69-
exit();
70-
}else{
71-
$this->logger->error("could not fork");
72-
exit();
73-
}
74-
});
75-
76-
$child = new \EvChild(0, false, function ($child, $revents) {
77-
pcntl_waitpid($child->rpid, $status);
78-
$message = "process exit. pid:" . $child->rpid . ". exit code:" . $child->rstatus;
79-
$this->logger->info($message);
80-
});
8132

82-
\Ev::run();
83-
$this->logger->info("crontab exit");
33+
parent::__construct($logger);
8434
}
8535
}

0 commit comments

Comments
 (0)