引言:为何需要毫秒级定时任务
在软件开发过程中,若业务涉及定时任务,通常首选Linux系统的crontab工具。然而,crontab的最小时间单位为分钟,无法处理秒级甚至毫秒级的精细调度需求。幸运的是,Swoole框架提供了功能强大的异步毫秒定时器,能够完美解决这一痛点。
典型应用场景分析
应用场景举例
在实际开发中,我们常遇到以下需要高精度调度的场景:
场景一:每隔30秒获取一次本机内存使用率
场景二:在特定时间点(如2分钟后)执行报表发送任务
场景三:每天凌晨2点定时请求第三方接口。若接口有数据返回则停止任务;若无响应或无数据,则等待5分钟后重试,最多尝试5次,失败后终止任务。
上述三个场景均属于典型的定时任务范畴,但传统工具难以优雅地满足其灵活性要求。
Swoole毫秒定时器API详解
Swoole毫秒定时器
Swoole提供了一系列异步毫秒定时器函数,支持高精度的时间控制:
swoole_timer_tick(int $msec, callable $callback):设置一个间隔时钟定时器,每隔$msec毫秒执行一次$callback回调函数,其行为类似于JavaScript中的setInterval()。
swoole_timer_after(int $after_time_ms, mixed $callback_function):在指定的时间$after_time_ms毫秒后执行$callback_function回调函数,类似于JavaScript的setTimeout()。
swoole_timer_clear(int $timer_id):删除指定id的定时器,类似于JavaScript的clearInterval()。
基于Swoole的解决方案对比
解决方案
针对场景一,这类需求常见于系统性能监控,对实时性要求较高且需控制频率。例如每30秒或10秒获取一次内存使用率,并生成可视化图表。相比之下,crontab最小只能设置为1分钟,无法满足此类高频监测需求。
swoole_timer_tick(30000, function($timer) use ($task_id) { // 启用定时器,每30秒执行一次
$memPercent = $this->getMemoryUsage(); //计算内存使用率
echo date('Y-m-d H:i:s') . '当前内存使用率:'.$memPercent."\n";
});
针对场景二,若需定义xx时间后执行某项任务,crontab实现较为困难。使用Swoole的可以轻松实现延时执行逻辑。
swoole_timer_after(120000, function() use ($str) { //2分钟后执行
$this->sendReport(); //发送报表
echo "send report, $str\n";
});
针对场景三,用于智能重试请求。失败后继续尝试,成功则停止。虽然crontab可通过固定间隔(如每5分钟)轮询来实现,但无论成功与否都会执行,效率低下。而Swoole定时器可根据业务结果动态控制,更加智能高效。
swoole_timer_tick(5*60*1000, function($timer) use ($url) { // 启用定时器,每5分钟执行一次
$rs = $this->postUrl($url);
if ($rs) {
//业务代码...
swoole_timer_clear($timer); // 停止定时器
echo date('Y-m-d H:i:s'). "请求接口任务执行成功\n";
} else {
echo date('Y-m-d H:i:s'). "请求接口失败,5分钟后再次尝试\n";
}
});
代码实现与验证
示例代码
新建文件\src\App\Task.php:
namespace Helloweba\Swoole;
use swoole_server;
/**
* 任务调度
*/
class Task
{
protected $serv;
protected $host = '127.0.0.1';
protected $port = 9506;
// 进程名称
protected $taskName = 'swooleTask';
// PID路径
protected $pidPath = '/run/swooletask.pid';
// 设置运行时参数
protected $options = [
'worker_num' => 4, //worker进程数,一般设置为CPU数的1-4倍
'daemonize' => true, //启用守护进程
'log_file' => '/data/log/swoole-task.log', //指定swoole错误日志文件
'log_level' => 0, //日志级别 范围是0-5,0-DEBUG,1-TRACE,2-INFO,3-NOTICE,4-WARNING,5-ERROR
'dispatch_mode' => 1, //数据包分发策略,1-轮询模式
'task_worker_num' => 4, //task进程的数量
'task_ipc_mode' => 3, //使用消息队列通信,并设置为争抢模式
];
public function __construct($options = [])
{
date_default_timezone_set('PRC');
// 构建Server对象,监听127.0.0.1:9506端口
$this->serv = new swoole_server($this->host, $this->port);
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
$this->serv->set($this->options);
// 注册事件
$this->serv->on('Start', [$this, 'onStart']);
$this->serv->on('Connect', [$this, 'onConnect']);
$this->serv->on('Receive', [$this, 'onReceive']);
$this->serv->on('Task', [$this, 'onTask']);
$this->serv->on('Finish', [$this, 'onFinish']);
$this->serv->on('Close', [$this, 'onClose']);
}
public function start()
{
// Run worker
$this->serv->start();
}
public function onStart($serv)
{
// 设置进程名
cli_set_process_title($this->taskName);
//记录进程id,脚本实现自动重启
$pid = "{$serv->master_pid}\\n{$serv->manager_pid}";
file_put_contents($this->pidPath, $pid);
}
//监听连接进入事件
public function onConnect($serv, $fd, $from_id)
{
$serv->send( $fd, "Hello {$fd}!" );
}
// 监听数据接收事件
public function onReceive(swoole_server $serv, $fd, $from_id, $data)
{
echo "Get Message From Client {$fd}:{$data}\n";
//$this->writeLog('接收客户端参数:'.$fd .'-'.$data);
$res['result'] = 'success';
$serv->send($fd, json_encode($res)); // 同步返回消息给客户端
$serv->task($data); // 执行异步任务
}
/**
* @param $serv swoole_server swoole_server对象
* @param $task_id int 任务id
* @param $from\id int 投递任务的worker_id
* @param $data string 投递的数据
*/
public function onTask(swoole_server $serv, $task_id, $from_id, $data)
{
swoole_timer_tick(30000, function($timer) use ($task_id) { // 启用定时器,每30秒执行一次
$memPercent = $this->getMemoryUsage();
echo date('Y-m-d H:i:s') . '当前内存使用率:'.$memPercent."\n";
});
}
/**
* @param $serv swoole_server swoole_server对象
* @param $task_id int 任务id
* @param $data string 任务返回的数据
*/
public function onFinish(swoole_server $serv, $task_id, $data)
{
//
}
// 监听连接关闭事件
public function onClose($serv, $fd, $from_id) {
echo "Client {$fd} close connection\n";
}
public function stop()
{
$this->serv->stop();
}
private function getMemoryUsage()
{
// MEMORY
if (false === ($str = @file("/proc/meminfo"))) return false;
$str = implode("", $str);
preg_match_all("/MemTotal\s{0,}\:+\s{0,}([\d\.]+).+?MemFree\s{0,}\:+\s{0,}([\d\.]+).+?Cached\s{0,}\:+\s{0,}([\d\.]+).+?SwapTotal\s{0,}\:+\s{0,}([\d\.]+).+?SwapFree\s{0,}\:+\s{0,}([\d\.]+)/s", $str, $buf);
//preg_match_all("/Buffers\s{0,}\:+\s{0,}([\d\.]+)/s", $str, $buffers);
$memTotal = round($buf[1][0]/1024, 2);
$memFree = round($buf[2][0]/1024, 2);
$memUsed = $memTotal - $memFree;
$memPercent = (floatval($memTotal)!=0) ? round($memUsed/$memTotal*100,2):0;
return $memPercent;
}
}
以场景一为例,在onTask回调中启用定时任务,每隔30秒计算一次内存使用率。实际应用中,可将计算结果按时间写入数据库等存储介质,供前端渲染统计图表使用。核心逻辑如下:

接着是服务端代码 public\taskServer.php :
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use Helloweba\Swoole\Task;
$opt = [
'daemonize' => false
];
$ser = new Task($opt);
$ser->start();
客户端代码 public\taskClient.php :
<?php
class Client
{
private $client;
public function __construct() {
$this->client = new swoole_client(SWOOLE_SOCK_TCP);
}
public function connect() {
if( !$this->client->connect("127.0.0.1", 9506 , 1) ) {
echo "Error: {$this->client->errMsg}[{$this->client->errCode}]\n";
}
fwrite(STDOUT, "请输入消息 Please input msg:");
$msg = trim(fgets(STDIN));
$this->client->send( $msg );
$message = $this->client->recv();
echo "Get Message From Server:{$message}\n";
}
}
$client = new Client();
$client->connect();
验证效果
1.启动服务端:
php taskServer.php
2.客户端输入:
另开命令行窗口,执行
[root@localhost public]# php taskClient.php
请输入消息 Please input msg:hello
Get Message From Server:{"result":"success"}
[root@localhost public]#
3.服务端返回:

如果返回上图中的结果,则表明定时任务正常运行。我们会发现每隔30秒会输出一条包含当前时间的信息,证明毫秒级定时器已生效。
总结
到此这篇关于php使用Swoole实现毫秒级定时任务的方法的文章就介绍到这了,更多相关php Swoole实现毫秒级定时任务内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!