tp5 +swoole 定时任务

毫秒级定时器实现
本文介绍如何在项目中使用swoole定时器实现毫秒级的定时任务,解决传统crontab仅支持分钟级定时的问题。通过配置swoole_server并结合swoole_timer_tick函数,可以精确控制定时任务的执行间隔。

 最近项目中需要用到毫秒级定时器,但是服务器中的crontab定时任务最小是分钟,所以使用了swoole的定时器。

需要先安装php swoole 扩展

<?php


namespace app\admin\command;

use app\admin\model\live\Log;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Exception;
use think\exception\ErrorException;

class Qdao extends Command
{
    #定时
    protected function configure()
    {
        $this->setName('qd')
            ->setDescription('qd');
    }
//    protected function execute(Input $input, Output $output)
//    {
//        $serv = new \swoole_server("0.0.0.0",9505);
//        $serv->on("WorkerStart",function ($serv,$woker_id){
//            if ($woker_id == 0){
//                //每隔1000ms触发一次
//                swoole_timer_tick(1000, function ($timer_id) {
//                    echo "hello\n";
//                });
//            }
//        });
//
//        $serv->on("receive",function ($serv,$fd,$from_id,$data){
//            $serv->send($fd,"Server:".$data);
//        });
//
//        $serv->start();
//    }
  
    protected function execute(Input $input, Output $output)
    {
        //每隔5分钟触发一次
        $id = \swoole_timer_tick(30000, function ($timer_id) {
            #逻辑程序

        });
        \Swoole\Event::wait();
    }
}

1.配置command.php文件,位于application/command.php 

configure函数是在命令行中用list命令列出所有任务的时候回显示的出的提示,execute函数是说要执行的命令,在这里可以直接调用其他函数,完成例如统计等任务工作,然后用output输出到命令行 

打开命令行,运行php think test命令test命令execute方法中运行的方法就会运行

要在 TP5 中结合 Swoole 实现定时任务,可以按照以下步骤进行: 1. 安装 Swoole 扩展:确保已经安装并启用了 Swoole 扩展,可以参考 Swoole 的官方文档进行安装。 2. 创建定时任务类:在 TP5 项目中创建一个定时任务类,例如 `app\command\Task`。在该类中,编写定时任务的逻辑代码。 ```php <?php namespace app\command; use think\console\Command; use think\console\Input; use think\console\Output; class Task extends Command { protected function configure() { $this->setName('task:run')->setDescription('Run the task'); } protected function execute(Input $input, Output $output) { // 定时任务逻辑代码 // 例如每隔一段时间执行某个任务 swoole_timer_tick(1000, function ($timer_id) { // 执行任务的代码 $output->writeln('Task executed...'); }); } } ``` 3. 注册定时任务:在 `app\command\command.php` 文件中注册定时任务。 ```php <?php return [ 'app\command\Task', ]; ``` 4. 运行定时任务:使用 Swoole 提供的 `swoole_timer_tick` 方法来运行定时任务。在 TP5 项目的根目录下,使用命令行工具运行定时任务。 ```shell php think swoole:task run ``` 以上步骤中的示例代码是一个简单的定时任务示例,每隔一秒钟执行一次任务,并输出一条日志。你可以根据实际需求修改定时任务的逻辑代码。 需要注意的是,定时任务是在 Swoole 服务器中运行的,所以你需要先启动 Swoole 服务器,然后再运行定时任务命令。
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梦夏夜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值