详情页

帝国cms定时审核功能中用swoole实现毫秒级审核/swoole中毫秒定时器(Timer)的使用

时间:2024年04月10日

编辑:佚名

前两天研究了一下帝国cms的定时审核,发现用定时审核插件配合宝塔计划任务中的定时访问url只能实现最低单位分钟的审核。很不爽。
研究了一下Swoole的毫秒定时器(Timer)的使用,觉得完美。以下是方法:
1、安装好自动审核插件
2、在PHP扩展里安装好swool扩展,我运行的是PHP7.4

安装完毕后重启PHP,运行
php --ri swoole
命令查看swool是否正确安装。
3、在PHP7.4运行的网站下任意位置创建PHP文件,自己随意命名。代码如下:
<?php
date_default_timezone_set('Asia/Shanghai'); // 设置正确的时区
// 要访问的URL
$url = 'https://www.78moban.com/e/admin/extend/whiletask/docheck.php?classid=news&pwd=ad888888';
// 定义开始和结束时间
$start_time = strtotime(date('Y-m-d') . ' 08:00:00');
$end_time   = strtotime(date('Y-m-d') . ' 22:00:00');
$logdir = __DIR__ . '/log'; // 使用当前脚本所在的目录
if (!is_dir($logdir)) {
    mkdir($logdir, 0777, true);
}
// 清理旧的日志文件
foreach (glob("$logdir/*.log") as $logfile) {
    if (filemtime($logfile) < strtotime('-3 days')) {
        unlink($logfile);
    }
}
\Swoole\Timer::tick(188 * 1000, function($timer_id) use ($url, $start_time, $end_time, $logdir) {
    $current_time = time();
    // 检查当前时间是否在指定的范围内
    if ($current_time > $start_time && $current_time < $end_time) {
        file_get_contents($url); // 访问URL
        // 记录日志
        $logfile = "$logdir/" . date('Y-m-d') . '.log';
        $log = date('H:i:s') . " - 访问了URL: $url\n";
        file_put_contents($logfile, $log, FILE_APPEND);
    } else {
        // 如果不在时间范围内,则停止定时器
        \Swoole\Timer::clear($timer_id);
        // 记录日志
        $logfile = "$logdir/" . date('Y-m-d') . '.log';
        $log = date('H:i:s') . " - 停止了定时器\n";
        file_put_contents($logfile, $log, FILE_APPEND);
    }
});
\Swoole\Event::wait();
?>
说明:https://www.78moban.com/e/admin/extend/whiletask/docheck.php?classid=news&pwd=ad888888 改为你自己定时审核插件的审核访问url地址。以上代码中我设置了每天早8点到晚22点,每隔188秒访问一次url,大哥们可以根据自己的需要调整时间,期中1秒=1000毫秒,自己改。
4、宝塔面板设置:
计划任务 – Shell脚本 – 任务名称(自拟)- 执行周期(每天几点开始)- 脚本内容(代码如下):
/www/server/php/74/bin/php /www/wwwroot/sh.78moban.com/xxxx.php
说明:/www/server/php/74/bin/php 是你对应的PHP版本安装路径,/www/wwwroot/sh.78moban.com/xxxx.php 是以上PHP文件的存放路径
添加任务,大功告成!
附:如果任务已经执行,如何结束它呢?首先,你需要找到这个PHP脚本的进程ID。你可以使用ps命令配合grep命令来搜索这个进程。下面是一个示例命令:
ps aux | grep xxxx.php
xxxx.php是你运行的Php文件名
然后使用以下代码来结束它:
kill 12345
请用你的实际进程ID替换上面的12345
如果进程不能被正常结束,你可以尝试使用kill命令的-9选项强制结束进程:
kill -9 12345
////////////////////////////////////////////////////////////////////////////////
宝塔面板添加计划任务 shell脚本  脚本内容:/www/wwwroot/sh.78moban.com/1/check.sh
check.sh内容
#!/bin/bash
# 要执行的脚本命令
command="/www/server/php/74/bin/php /www/wwwroot/sh.78moban.com/1/shenhe.php"
# 检查是否已经有相同的进程在运行
count=$(ps aux | grep "$command" | grep -v grep | wc -l)
if [ $count -gt 0 ]; then
    echo "已经有相同的进程在运行"
else
    # 执行脚本命令
    eval $command
    exit_code=$?
    if [ $exit_code -eq 0 ]; then
        echo "恭喜,任务执行成功!"
    else
        echo "任务执行失败,错误码:$exit_code"
    fi
fi
相关文章
猜你需要