From a98fbdc7a16134d7111f41d903d1196be3eb1c49 Mon Sep 17 00:00:00 2001 From: JaguarJack Date: Wed, 16 Sep 2020 10:08:05 +0800 Subject: [PATCH] =?UTF-8?q?add=EF=BC=9A=E6=96=B0=E5=A2=9E=E5=AE=9A?= =?UTF-8?q?=E6=97=B6=E4=BB=BB=E5=8A=A1=E5=9F=BA=E7=B1=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extend/catcher/base/CatchCronTask.php | 92 +++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/extend/catcher/base/CatchCronTask.php b/extend/catcher/base/CatchCronTask.php index ef90e0a..e6aa84f 100644 --- a/extend/catcher/base/CatchCronTask.php +++ b/extend/catcher/base/CatchCronTask.php @@ -8,3 +8,95 @@ // +---------------------------------------------------------------------- // | Author: JaguarJack [ njphper@gmail.com ] // +---------------------------------------------------------------------- +namespace catcher\base; + +use catchAdmin\monitor\model\CrontabLog; + +abstract class CatchCronTask +{ + protected $exceptionHappenTimes = 0; + + protected $exitTimes = 1; + + protected $crontab; + + /** + * @time 2020年07月29日 + * @return mixed + */ + public abstract function deal(); + + /** + * @time 2020年07月29日 + * @param \Throwable $e + * @return mixed + */ + public abstract function dealWithException(\Throwable $e); + + /** + * 执行 + * + * @time 2020年07月23日 + * @return void|bool + */ + public function run() + { + $startAt = round(microtime(true) * 1000); + try { + if ($this->deal() === false) { + return false; + } + $this->recordLog($startAt); + return true; + } catch (\Throwable $e) { + $this->dealWithException($e); + echo 'File:' . $e->getFile() . ', Lines: '. $e->getLine() .'行,Exception Message: ' . $e->getMessage() . PHP_EOL; + // 输出堆栈信息 + echo $e->getTraceAsString() . PHP_EOL; + // 日志记录 + $this->recordLog($startAt, 'File:' . $e->getFile() . ', Lines: '. $e->getLine() .'行,Exception Message: ' . $e->getMessage()); + $this->exceptionHappenTimes += 1; + } + + + } + + /** + * 退出 + * + * @time 2020年07月29日 + * @return bool + */ + public function shouldExit() + { + // var_dump($this->exceptionHappenTimes); + return $this->exceptionHappenTimes > $this->exitTimes; + } + + /** + * 设置 crontab + * + * @time 2020年09月15日 + * @param array $crontab + * @return $this + */ + public function setCrontab(array $crontab) + { + $this->crontab = $crontab; + + return $this; + } + + protected function recordLog($startAt, $message = '') + { + $endAt = round(microtime(true) * 1000); + CrontabLog::insert([ + 'crontab_id' => $this->crontab['id'], + 'used_time' => $endAt - $startAt, + 'error_message' => $message, + 'status' => $message ? CrontabLog::FAILED : CrontabLog::SUCCESS, + 'created_at' => time(), + 'updated_at' => time(), + ]); + } +} \ No newline at end of file