相关推荐recommended
thinkphp开启定时任务的三种办法(最全)
作者:mmseoamin日期:2024-02-04

第一种方法

使用think-cron类库

//composer 安装

composer require yunwuxin/think-cron

github文档地址

https://github.com/yunwuxin/think-cron

1.创建任务类

namespace app\task;

use yunwuxin\cron\Task;

class DemoTask extends Task

{

    public function configure()

    {

        $this->daily(); //设置任务的周期,每天执行一次,更多的方法可以查看源代码,都有注释

    }

    /**

     * 执行任务

     * @return mixed

     */

    protected function execute()

    {

        //...具体的任务执行

    }

}

2.配置文件 application/extra/cron.php

return [

    'tasks' => [

        \app\task\DemoTask::class, //任务的完整类名

    ]

];

3.开启任务监听

#方法一 (推荐)

起一个常驻进程,可以配合supervisor使用

php think cron:schedule

#方法二

在系统的计划任务里添加

* * * * * php /path/to/think cron:run >> /dev/null 2>&1

第二种办法

自己手写方法

thinkphp开启定时任务的三种办法(最全),第1张

1.在app下创建command文件夹,写一个timedTask.php文件

namespace app\command;

 

use think\console\Command;

use think\console\Input;

use think\console\Output;

use think\Db;

use think\Log;

 

class timedTask extends Command

{

    protected function configure(){

        $this->setName('SendMessage')->setDescription("计划任务 SendMessage");

    }

 

    //调用SendMessage 这个类时,会自动运行execute方法

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

        $output->writeln('Date Crontab job start...');

        /*** 这里写计划任务列表集 START ***/

 

        $this->test();

 

        /*** 这里写计划任务列表集 END ***/

        $output->writeln('Date Crontab job end...');

    }

 

    //获取当天生日的员工 发短信

    public function test()

    {

        Db::name('log')->insert([

            'content'      => '定时发起',

            'add_time'       => time(),

            'uid'       => 1,

            'code'  => '1000',

            'title'  => '定时任务'

        ]);

        //echo '这里写你要实现的逻辑代码';

    }

}

?>

2.在app/command.php里面加上

    return ['app\command\timedTask'];

1

3.运行SendMessage命令,查看代码是否可运行

进入服务器,进入项目目录

执行命令

php think SendMessage

设置crontab计划任务

#服务器无宝塔

注:

crontab -l //计划任务列表

crontab -e //编辑新增

crontab -r //删除

执行crontab -e,添加下面的定时任务,每隔1分钟执行一次后面的命令

*/1 * * * *  php 项目路径/think 设置的命令关键字 

thinkphp开启定时任务的三种办法(最全),第2张

第三种方法

#服务器有宝塔

直接添加计划任务就可以了

thinkphp开启定时任务的三种办法(最全),第3张

如果您觉得本篇对你有帮助,可以点关注,给个赞,支持一下,过程有遇到什么问题也欢迎评论私信,进行交流