thinkphp中使用计划任务

一、需求

数据库有两个字段enter_time入驻时间与status状态,当入驻时间超过指定时间时,要求将状态设置为指定状态。

二、解决方案

方案1:使用计划任务,定时判断入驻时间是否超过指定时间。

github库:think-cron(GitHub - yunwuxin/think-cron: 计划任务 for thinkphp

1、安装think-cron

composer require yunwuxin/think-cron
版本原因安装失败,尝试使用:
composer require yunwuxin/think-cron:*

2、创建任务类

<?php

namespace app\task;

use yunwuxin\cron\Task;

class DemoTask extends Task
{

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

    /**
     * 执行任务
     * @return mixed
     */
    protected function execute()
    {
        //...具体的任务执行
    }
}

新建一个目录task,再新建一个任务类。

 

3、在配置文件中注册任务

 

4、监听任务 

 方法一 (推荐)

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

php think cron:schedule

 方法二

在系统的计划任务里添加 

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

 补充:

1、使用以下命令,可执行一次任务。

php think cron:run

2、从源码中可以看到一共有两个命令 

 

3、可以了解到think-cron的计划任务逻辑 

如下图,每60秒执行一遍php think cron:run,而在php think cron:run命令中判断当前执行时的时间是否满足条件,满足则执行任务。

 

4、在windows环境

建议去掉Schedule.phpexecute函数中的start /B,否则当执行php think cron:schedule时,到时间会弹出弹窗询问是否打开文件,如下图。

 

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐