95 lines
3.1 KiB
PHP
95 lines
3.1 KiB
PHP
<?php
|
||
|
||
/**
|
||
|
||
|
||
|
||
|
||
|
||
|
||
*/
|
||
|
||
namespace app\event\init;
|
||
|
||
use app\dict\system\ScheduleDict;
|
||
use app\model\system\Cron;
|
||
use think\facade\Cache;
|
||
|
||
/**
|
||
* 初始化计划任务启动
|
||
* @author Administrator
|
||
*
|
||
*/
|
||
class InitCron
|
||
{
|
||
public function handle()
|
||
{
|
||
log_write('InitCron计划任务初始化', 'debug');
|
||
try {
|
||
//根据计划任务类型来判断
|
||
if (config('cron.default') != ScheduleDict::default) {
|
||
log_write('InitCron计划任务未开启', 'warning');
|
||
return;
|
||
}
|
||
if (defined('BIND_MODULE') && BIND_MODULE === 'install') {
|
||
log_write('InitCron计划任务未开启,安装模块时不执行计划任务', 'warning');
|
||
return;
|
||
}
|
||
$last_time = Cache::get("cron_last_load_time");
|
||
if (empty($last_time)) {
|
||
$last_time = 0;
|
||
}
|
||
$last_exec_time = Cache::get("cron_http_last_exec_time");
|
||
if (empty($last_exec_time)) {
|
||
$last_exec_time = 0;
|
||
}
|
||
$module = request()->module();
|
||
if ($module == 'cron') {
|
||
log_write('InitCron计划任务未开启, 请求模块是 cron 模块', 'warning');
|
||
return;
|
||
}
|
||
|
||
$enable_start = !defined('CRON_EXECUTE') && time() - $last_time > 100 && time() - $last_exec_time > 100;
|
||
|
||
if (!$enable_start) {
|
||
$content = sprintf('InitCron计划任务未启动,[%s, %s, %s], cron_last_load_time: %s, cron_http_last_exec_time: %s, CRON_EXECUTE:%s',
|
||
!defined('CRON_EXECUTE') ? '1' : '0',
|
||
time() - $last_time > 100 ? '1' : '0',
|
||
time() - $last_exec_time > 100 ? '1' : '0',
|
||
date('Y-m-d H:i:s', $last_time),
|
||
date('Y-m-d H:i:s', $last_exec_time),
|
||
defined('CRON_EXECUTE') ? 'true' : 'false'
|
||
);
|
||
log_write($content, 'debug');
|
||
return;
|
||
}
|
||
|
||
Cache::set("cron_http_last_exec_time", time());
|
||
defined('CRON_EXECUTE') or define('CRON_EXECUTE', 1);
|
||
$url = url('cron/task/cronExecute');
|
||
$ch = curl_init();
|
||
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
|
||
curl_setopt($ch, CURLOPT_HEADER, true);
|
||
curl_setopt($ch, CURLOPT_URL, $url);
|
||
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
|
||
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
|
||
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
|
||
curl_exec($ch);
|
||
|
||
// 获取错误信息并打印
|
||
$error = curl_error($ch);
|
||
if ($error) {
|
||
//保存错误
|
||
Cron::setError(ScheduleDict::default, $error);
|
||
}
|
||
// 关闭cURL资源句柄
|
||
curl_close($ch);
|
||
log_write('InitCron计划任务已启动', 'debug');
|
||
} catch (\Exception $e) {
|
||
// 计划任务异常,直接返回
|
||
log_write('InitCron计划任务异常:' . $e->getMessage(), 'error');
|
||
return;
|
||
}
|
||
}
|
||
}
|