我是靠谱客的博主 名字长了才好记,这篇文章主要介绍ThinkPHP中写一个定时任务,现在分享给大家,希望可以做个参考。

想在ThinkPHP中写一个定时任务,又不想这个任务是一个可以外网访问的地址怎么办?

ThinkPHP中提供了创建自定义指令的方法

参考官方示例:传送门

在命令台下

复制代码
1
php think make:command Hello hello

会生成一个 app\command\Hello 命令行指令类

在目标文件中打开,我们稍作修改

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php declare (strict_types=1); /**  * for command test  * @author wolfcode  * @time 2020-06-04  */ 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')             ->addArgument('name', Argument::OPTIONAL, "your name")             ->addOption('city', null, Option::VALUE_REQUIRED, 'city name')             ->setDescription('the hello command');     }     protected function execute(Input $input, Output $output)     {         $name = $input->getArgument('name');         $name = $name ?: 'wolfcode';         $city = '';         if ($input->hasOption('city')) {             $city = PHP_EOL . 'From ' . $input->getOption('city');         }         // 指令输出         $output->writeln("hello {$name}" . '!' . $city);     } }

同时记得去注册下命令

在项目 config/console.php 中的'commands'加入

复制代码
1
2
3
4
5
6
<?php  return [   'commands' => [         'hello' => \app\command\Hello::class,   ] ];

官方的写法是下面这样的(但是我按照这样写会报错)

复制代码
1
2
3
4
5
6
<?php  return [   'commands' => [         'hello' => 'app\command\Hello',   ] ];

配置完后就可以在命令台中测试了

复制代码
1
php think hello

输出

复制代码
1
hello wolfcode!

定时任务需要的代码写完了,现在加入到crontab中

首先先查找下当前php命令所在的文件夹

复制代码
1
type -p grep php

例如在 /usr/local/bin/php,则 crontab -e 中可以这样写:(文件会越来越大)

复制代码
1
* * * * * /usr/local/bin/php /path/yourapp/think hello>>/path/yourlog/hello.log 2>&1

如果你想把日志分成每天来单独记录,可以这样写:

复制代码
1
* * * * * /usr/local/bin/php /path/yourapp/think hello>>/path/yourlog/hello_`date -d 'today' +\%Y-\%m-\%d`.log 2>&1

然后检查下 crontab -l 是否填写正常,最后去 /path/yourlog下 看看你的定时任务日志是否运行正常!


最后

以上就是名字长了才好记最近收集整理的关于ThinkPHP中写一个定时任务的全部内容,更多相关ThinkPHP中写一个定时任务内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(147)

评论列表共有 0 条评论

立即
投稿
返回
顶部