Files
2026-06-11 16:22:12 +08:00

306 lines
9.6 KiB
PHP

<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台(PHP版)
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
// | 开源版本可自由商用,可去除界面版权logo
// | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
// | github下载:https://github.com/likeshop-github/likeadmin
// | 访问官网:https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------
namespace app\adminapi\logic\crontab;
use app\common\enum\CrontabEnum;
use app\common\logic\BaseLogic;
use app\common\model\Crontab;
use app\common\model\CrontabLog;
use Cron\CronExpression;
/**
* 定时任务逻辑层
* Class CrontabLogic
* @package app\adminapi\logic\crontab
*/
class CrontabLogic extends BaseLogic
{
private const CRAWLER_MIGRATED_MESSAGE = 'crawler任务已迁移到Docker容器调度,请查看管理端爬虫任务日志';
private const CRAWLER_MIGRATED_COMMANDS = [
'crawler',
'truth_social',
'fifa_worldcup_news',
];
/**
* @notes 添加定时任务
* @param $params
* @return bool
* @author 段誉
* @date 2022/3/29 14:41
*/
public static function add($params)
{
try {
$params['remark'] = $params['remark'] ?? '';
$params['params'] = $params['params'] ?? '';
$params['last_time'] = time();
Crontab::create($params);
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 查看定时任务详情
* @param $params
* @return array
* @author 段誉
* @date 2022/3/29 14:41
*/
public static function detail($params)
{
$field = 'id,name,type,type as type_desc,command,params,status,status as status_desc,expression,remark';
$crontab = Crontab::field($field)->findOrEmpty($params['id']);
if ($crontab->isEmpty()) {
return [];
}
return $crontab->toArray();
}
/**
* @notes 编辑定时任务
* @param $params
* @return bool
* @author 段誉
* @date 2022/3/29 14:42
*/
public static function edit($params)
{
try {
$params['remark'] = $params['remark'] ?? '';
$params['params'] = $params['params'] ?? '';
Crontab::update($params);
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 删除定时任务
* @param $params
* @return bool
* @author 段誉
* @date 2022/3/29 14:42
*/
public static function delete($params)
{
try {
Crontab::destroy($params['id']);
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 操作定时任务
* @param $params
* @return bool
* @author 段誉
* @date 2022/3/29 14:42
*/
public static function operate($params)
{
try {
$crontab = Crontab::findOrEmpty($params['id']);
if ($crontab->isEmpty()) {
throw new \Exception('定时任务不存在');
}
switch ($params['operate']) {
case 'start';
$crontab->status = CrontabEnum::START;
break;
case 'stop':
$crontab->status = CrontabEnum::STOP;
break;
}
$crontab->save();
return true;
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
/**
* @notes 获取规则执行时间
* @param $params
* @return array|string
* @author 段誉
* @date 2022/3/29 14:42
*/
public static function run($params)
{
try {
$crontab = Crontab::findOrEmpty($params['id']);
if ($crontab->isEmpty()) {
throw new \Exception('定时任务不存在');
}
if (in_array($crontab->command, self::CRAWLER_MIGRATED_COMMANDS, true)) {
Crontab::where('id', $crontab->id)->update([
'error' => self::CRAWLER_MIGRATED_MESSAGE,
]);
throw new \Exception(self::CRAWLER_MIGRATED_MESSAGE);
}
$log = CrontabLog::create([
'crontab_id' => $crontab->id,
'name' => $crontab->name,
'command' => $crontab->command,
'params' => $crontab->params,
'status' => 0,
'output' => '',
'elapsed' => 0,
'trigger_type' => 2,
]);
if ($crontab->command === 'truth_social') {
$crawlerDir = app()->getRootPath() . 'public/dongqiudi-crawler';
$python = 'python3';
$logId = $log->id;
$crontabId = $crontab->id;
$cmd = "cd {$crawlerDir} && nohup {$python} main.py truth_social --log-id={$logId} --crontab-id={$crontabId} > /dev/null 2>&1 &";
\shell_exec($cmd);
return ['log_id' => $logId, 'output' => '任务已提交,后台执行中...', 'async' => true];
}
if ($crontab->command === 'fifa_worldcup_news') {
$crawlerDir = app()->getRootPath() . 'public/dongqiudi-crawler';
$python = 'python3';
$logId = $log->id;
$crontabId = $crontab->id;
$cmd = "cd {$crawlerDir} && nohup {$python} main.py fifa_worldcup_news --log-id={$logId} --crontab-id={$crontabId} > /dev/null 2>&1 &";
\shell_exec($cmd);
return ['log_id' => $logId, 'output' => '任务已提交,后台执行中...', 'async' => true];
}
$startTime = microtime(true);
try {
ob_start();
$params_arr = explode(' ', $crontab->params);
if (is_array($params_arr) && !empty($crontab->params)) {
\think\facade\Console::call($crontab->command, $params_arr);
} else {
\think\facade\Console::call($crontab->command);
}
$outputStr = ob_get_clean() ?: '';
$elapsed = round(microtime(true) - $startTime, 2);
$log->save([
'status' => 1,
'output' => mb_substr($outputStr ?: '执行完成', 0, 5000),
'elapsed' => $elapsed,
]);
Crontab::where('id', $crontab->id)->update([
'last_time' => time(),
'time' => $elapsed,
'error' => '',
]);
return ['log_id' => $log->id, 'output' => $outputStr ?: '执行完成', 'elapsed' => $elapsed];
} catch (\Exception $e) {
$elapsed = round(microtime(true) - $startTime, 2);
$log->save([
'status' => 2,
'output' => $e->getMessage(),
'elapsed' => $elapsed,
]);
Crontab::where('id', $crontab->id)->update([
'error' => $e->getMessage(),
'status' => CrontabEnum::ERROR,
]);
throw $e;
}
} catch (\Exception $e) {
self::setError($e->getMessage());
return false;
}
}
public static function logs($params)
{
$where = [];
if (!empty($params['crontab_id'])) {
$where[] = ['crontab_id', '=', $params['crontab_id']];
}
$pageNo = max(1, intval($params['page_no'] ?? 1));
$pageSize = min(100, max(1, intval($params['page_size'] ?? 20)));
$offset = ($pageNo - 1) * $pageSize;
$lists = CrontabLog::where($where)
->order('id', 'desc')
->limit($offset, $pageSize)
->select()
->toArray();
foreach ($lists as &$item) {
$item['create_time'] = !empty($item['create_time']) ? (is_numeric($item['create_time']) ? date('Y-m-d H:i:s', intval($item['create_time'])) : $item['create_time']) : '-';
$item['status_text'] = match ((int) $item['status']) {
0 => '执行中',
1 => '成功',
2 => '失败',
default => '未知',
};
$item['trigger_type_text'] = $item['trigger_type'] == 2 ? '手动' : '自动';
}
$count = CrontabLog::where($where)->count();
return ['lists' => $lists, 'count' => $count];
}
public static function expression($params)
{
try {
$cron = new CronExpression($params['expression']);
$result = $cron->getMultipleRunDates(5);
$result = json_decode(json_encode($result), true);
$lists = [];
foreach ($result as $k => $v) {
$lists[$k]['time'] = $k + 1;
$lists[$k]['date'] = str_replace('.000000', '', $v['date']);
}
$lists[] = ['time' => 'x', 'date' => '……'];
return $lists;
} catch (\Exception $e) {
return $e->getMessage();
}
}
}