thinkphp定时任务

第一种方法

使用think-cron类库

composer require yunwuxin/think-cron

github文档地址

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

第二种办法

自己手写方法
1.在app下创建command文件夹,写一个timedTask.php文件
thinkphp定时任务_第1张图片

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'];

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

进入服务器,进入项目目录
执行命令
php think SendMessage

4.设置crontab计划任务

#服务器无宝塔
注:
crontab -l //计划任务列表
crontab -e //编辑新增
crontab -r //删除

执行crontab -e,添加下面的定时任务,每隔1分钟执行一次后面的命令
*/1 * * * *  php 项目路径/think 设置的命令关键字 

thinkphp定时任务_第2张图片
#服务器有安装宝塔
直接添加计划任务就可以了
thinkphp定时任务_第3张图片

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

你可能感兴趣的:(php学习笔记)