ThinkPHP5实现定时器任务

22 篇文章 0 订阅
2 篇文章 0 订阅
本文介绍了两种在ThinkPHP中实现命令行任务和定时调度的方法。方法一涉及创建自定义命令类,通过`think`命令执行,并在`crontab`中设置定时任务。方法二则是通过创建Controller类并编写对应方法,然后同样用`crontab`进行定时调度。两种方法均可实现定时功能,选择取决于个人习惯。
摘要由CSDN通过智能技术生成

方法一

1.在/application/command创建要配置的PHP类文件,需要继承Command类,并重写configure和execute两个方法,例如:

<?php

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class Hello extends Command
{
    protected function configure()
    {
        $this->setName('hello')    //命令的名字("think" 后面的部分)
            ->addArgument('name', Argument::REQUIRED, "your name")    //必填参数
            ->addArgument('last_name', Argument::OPTIONAL, 'Your last name?')    //选填参数
            ->addOption('city', 'c', Option::VALUE_OPTIONAL, 'city name')    
            ->setDescription('Say Hello');    // 运行 "php think list" 时的简短描述
            ->setHelp("This command allows you to create users...");    // 运行命令时使用 "--help" 选项时的完整命令描述
    }

    protected function execute(Input $input, Output $output)
    {
        $name = trim($input->getArgument('name'));
        $name = $name ?: 'thinkphp';
        $other = trim($input->getArgument('last_name'));
        $other = $other ?: 'last';

        if ($input->hasOption('city')) {
            $city = PHP_EOL . 'From ' . $input->getOption('city');
        } else {
            $city = '';
        }

        $output->writeln("Hello," . $name .'last_name->'.$other. '!' . $city);
    }
}

直接进入网站根目录,命令行执行,就可看到效果 

php think hello fujian min  --city xiamen

2.修改application/command.php内容,加入上述的定时器内容

<?php
return [
    'application\command\Hello', // 加入需要cmd运行的PHP文件
];

3.添加shell执行文件

在项目根目录下创建shell脚本,例如crond.sh

#!/bin/sh
PATH=/usr/local/php/bin:/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin # 将php路径加入都临时变量中
# 如果你的PHP命令是已经配置了全局,可不需要上面这句
cd /home/wwwroot/域名/  # 进入项目的根目录下,保证可以运行php think的命令
php think hello xx # 执行在Hello.php设定的名称

注意:test 可执行命令是ThinkPHP自带的,可以通过 连接服务器,到/home/wwwroot/域名/ 目录下,输入 php think查询可以被执行的命令,如下:

4.使用crontab设置定时器

有两种方式,效果是一样的:

1.连接到服务器,输入 crontab -e,写入:

0 0 * * * /home/wwwroot/域名/crond.sh

注意:1).0 0 * * * 是crontab的定时表达式,表示每天的0点0分执行该文件,具体详情可以访问《crontab定时写法》进行学习。

         2).可以使用crontab -l 的命令查看已登录的账户有几个定时器。

         3).可以到 /var/log/cron 文件查看日志文件,便于追踪错误。

2.连接到服务器,输入 vim /etc/crontab, 初始化内容为:

在该文件写入

0 0 * * * root /home/wwwroot/域名/crond.sh

最终的查看的结果是:

最后保存该文件

5.重启crond服务

service crond restart

如果 该命令无法重启,请使用systemctl restart crond 进行重启

----------------------------------------------------------分隔线--------------------------------------------------------------

方法二,需要修改本文的前三步,后面均一致。

1).新增Controller类,并编写相对应的方法,例如:

以下是Test Controller类,还有一个简单的test方法。

<?php

namespace app\demo\controller;

use think\Controller;
use think\Log;

class Test extends Controller
{
    public function test(){
        Log::error('start test  crond demo.....');
        Log::error('end test  crond demo.....');
    }

}

访问test方法的路由:demo/test/test

2).添加shell执行文件

在项目根目录下创建shell脚本,例如crond.sh

#!/bin/sh
PATH=/usr/local/php/bin:/opt/someApp/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
# 若配置全局PHP命令,可不需要上面这句
# 1.执行 php 命令不需要到thinkphp项目的目录下 2.index.php为入口文件 3.第三个参数为需要执行方法的路由
php /home/wwwroot/域名/index.php demo/test/test

后面的步骤从本文第4步开始,就可以完成定时功能。

第二种方法符合API引用的思维,可能比较容易理解,第一种是利用thinkPHP本身的一个功能,这两种都可以,看个人习惯。

ThinkPHP 6 中使用 Workerman 实现定时器可以通过添加自定义命令来实现。下面是一个简单的实现步骤: 1. 首先,确保你已经安装了 Workerman 和 think-worker 扩展。可以通过执行以下命令来安装它们: ``` composer require workerman/workerman think-worker ``` 2. 创建一个自定义的命令类来处理定时任务。在 app/command 目录下创建一个名为 Timer.php 的文件,并在该文件中编写以下代码: ```php <?php namespace app\command; use think\console\Command; use think\console\Input; use think\console\Output; class Timer extends Command { protected function configure() { $this->setName('timer:work')->setDescription('Workerman Timer'); } protected function execute(Input $input, Output $output) { $worker = new \Workerman\Worker(); $worker->onWorkerStart = function($worker) { // 在这里编写定时任务的处理逻辑 \Workerman\Lib\Timer::add(1, function() { echo "定时任务执行\n"; }); }; \Workerman\Worker::runAll(); } } ``` 3. 注册自定义命令。在 config/console.php 中的 commands 数组中添加命令类的命名空间路径: ```php 'commands' => [ 'app\command\Timer', ], ``` 4. 运行定时任务。通过执行以下命令来运行定时任务: ``` php think timer:work ``` 这样,定时任务就会在后台运行,并每秒钟执行一次。你可以在 `$worker->onWorkerStart` 回调函数中编写具体的定时任务逻辑。请根据自己的需求进行修改和扩展。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值