tp5定时任务

第一步:

a.App/模块/ 下创建command文件夹

b.我这边是创建在crontab模块里面,在command文件夹下创建一个Task.php文件(具体名字自己根据需求定)

c.复制下面的代码到Task.php

<?php
namespace app\crontab\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
class Task extends Command
{
    protected function configure()
    {
        $this->setName('task')
            ->setDescription('定时计划测试:每分钟插入一条数据');
    }

    protected function execute(Input $input, Output $output)
    {
        // 输出到日志文件
        $output->writeln("TestCommand:");
       // 定时器需要执行的内容
        $data = [
            'name'=>'zxm22',
            'addr'=>'上海'
        ];
        db('blog')->insert($data);
        $output->writeln("end....");
    }


}

第二步:在APP/command.php里面加上

 

 

 

第三步:在linux下设置crontab定时计划任务(我的项目文件放在/var/www/mytp5)即可

crontab -l //计划任务列表
crontab -e //编辑新增
crontab -r //删除

 

 可参照:(查看php执行路径  whereis php)

1、配置command.php文件,目录在application/command.php

2、建立命令类文件,新建application/index/command/Test.php

<?php
namespace app\index\command;
 
use think\console\Command;
use think\console\Input;
use think\console\Output;
 
class Test extends Command
{
    protected function configure()
    {
        $this->setName('test')->setDescription('Here is the remark ');
    }
 
    protected function execute(Input $input, Output $output)
    {
        $output->writeln("TestCommand:");
    }
}
3、命令行下运行php think test ,将输出 TestCommand:,说明命令行已经成功

4、在linux系统配置crontab定时任务,一般目录在下图

4、根据自己的用户角色,编辑文件,如我是root用户,打开root文件,配置contab

*/1 * * * * cd /项目路径 && /php路径/php think test >> tmp/test.log 2>&1

这句话的意思是没一分钟执行一遍 test/index,日志存储在项目目录的 tmp/test.log文件里

 

根据上面的步骤就可以把定时任务跑起来了,很简单吧!!!

 

posted @ 2019-11-02 15:16  艾薇-Ivy  阅读(7340)  评论(0编辑  收藏  举报