crontab 定时

tp 基于crontab实现定时任务

一.第一种方法

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

 <?php
  namespace app\command;
  use think\console\Command;
  use think\console\Input;
  use think\console\Output;
  use think\Db;

  class Test extends Command{

      // 配置定时器的信息
     protected function configure() {

         $this->setName('test') ->setDescription('Command Test');

    }

    protected function execute(Input $input, Output $output)  {

         // 输出到日志文件
         $output->writeln("TestCommand:");

         // 定时器需要执行的内容
         $output->writeln("end....");
     }
 }

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

<?php

     return [
        'application\command\Test', // 加入需要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路径加入都临时变量中
    cd /home/wwwroot/域名/  # 进入项目的根目录下,保证可以运行php think的命令
    php think test # 执行在Test.php设定的名称

4.使用crontab设置定时器
连接到服务器,输入 crontab -e,写入:

0 0 * * * /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

# 1.执行 php 命令不需要到thinkphp项目的目录下 2.index.php为入口文件 3.第三个参数为需要执行方法的路由

php /home/wwwroot/域名/index.php demo/test/test

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

文章转自http://www.cnblogs.com/seizemiss/p/9467558...

本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!