thinkphp5.0定时任务

来源:互联网 发布:下载会计软件多少钱 编辑:程序博客网 时间:2024/06/11 07:54

php定时任务

系统环境要求

  • linux环境
  • 装有at命令
  • thinkphp5.0框架

开发人员必须会的

  1. 必须知道使用linux命令
  2. 必须了解at命令
  3. 必须知道thinkphp5.0框架的命令行开发
  4. 可以自己搭建php环境

在ThinkPHP5.0框架中の根目录下存在如下文件

  1. think.php
  2. composer.json
  3. composer.lock

其中think.php就是我们需要使用到的文件。


具体实现

执行任务代码实现

1、打开终端
2、使用cd命令进入到项目根目录
3、进入到项目根目录后,输入命令行:

$ php think make:controller command/Task

4、然后可以看到application文件夹中多出了command文件夹,进入后可以看到Task.php文件

<?phpnamespace app\Command;use think\Controller;class Task extends Controller{    //}

5、接下来我们需要更改这个文件内容变为如下:

namespace app\command;use think\console\Command;use think\console\Input;use think\console\input\Argument;use think\console\Output;class Task extends Command{    protected function configure()    {        $this->addArgument('test1',Argument::REQUIRED);  #必须参数        $this->addArgument('test2',Argument::OPTIONAL);  #可选参数        $this->setName('test')->setDescription('Command Test');    }    protected function execute(Input $input, Output $output)    {        $test1 = $input->getArgument('test1');        $test2 = $input->getArgument('test2');        #逻辑代码        //todo         #输出代码        $output->writeln("TestCommand:test1=".json_encode($test1));        $output->writeln("TestCommand:test2=".json_encode($test2));    }}

6、回到application目录,找到command.php文件,增加新加入的类(包含命名空间)

return [    'app\command\Task',];

7、保存后,重新回到终端,输入:

$ php think listThink Console version 0.1Usage:  command [options] [arguments]Options:  -h, --help            Display this help message  -V, --version         Display this console version  -q, --quiet           Do not output any message      --ansi            Force ANSI output      --no-ansi         Disable ANSI output  -n, --no-interaction  Do not ask any interactive question  -v|vv|vvv, --verbose  Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debugAvailable commands:  build              Build Application Dirs  clear              Clear runtime file  help               Displays help for a command  list               Lists commands  test               Command Test  unit               phpunit make  make:controller    Create a new resource controller class  make:model         Create a new model class optimize  optimize:autoload  Optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production.  optimize:config    Build config and common file cache.  optimize:route     Build route cache.  optimize:schema    Build database schema cache.

8、可以看到Available commands:中有一个test命令,尝试键入

$ php think test  [RuntimeException]        #运行时异常  Not enough arguments.     #缺少参数

9、提示异常信息!

$ php think test aaa bbbTestCommand:test1="aaa"TestCommand:test2="bbb"

10、运行结果与预期结果一致。至此,执行任务的代码完成。


写定时任务代码实现

在application中创建工具类TimedTask

<?php/** * Created by PhpStorm. * User: Administrator * Date: 2017/12/8 0008 * Time: 上午 10:51 * Administrator */namespace app\util;/** * Class TimedTask * @package app\util */class TimedTask{    /**     * 执行定时任务     *     * @param $command string think框架的command命令  例如:test     * @param $time string 执行时间     * 例如:①1-i表示一分钟后执行   ②11am-time  上午11点     * 如传入具体时间 请使用格式 $time.'-time'     * 如果是多少单位后执行 请使用  $num .'-*' 注:*代表 date方法中除秒之外的各时间格式  比如Y代表年     * @param $argv string 执行参数  多个参数用空格隔离     * @return string|array 执行结果     */    public static function timingExecution ($command,$time,$argv){        list($num,$format) = explode('-',$time);        switch ($format){            case 'd':$execTime = 'now +'.$num.' days';break;            case 'm':$execTime = 'now +'.$num.' months';break;            case 'Y':$execTime = 'now +'.$num.' years';break;            case 'H':$execTime = 'now +'.$num.' hours';break;            case 'i':$execTime = 'now +'.$num.' minutes';break;            case 'time':$execTime = $num;        }        if (strtoupper(substr(PHP_OS,0,3))==='WIN'){            #todo windows下的定时任务改如何执行。        }else {            #其他系统            $result = system("echo 'php think " . $command.time() . " " . $argv . "'|" . 'at ' . $execTime . '');        }        return $result;    }}

参考at命令可以知道

>at 时间>任务命令>ctrl+d <EOF>

而at的时间是两种形式

1. now+1 days    #相对时间2. 08:00pm       #绝对时间

所以上面代码中的switch用来处理相对时间。
此代码并不支持绝对时间加相对时间的处理,有待优化。比如:

$ at 08:00am + 1 days   #表示1天后早上八点

欢迎大家讨论。

原创粉丝点击