第一步,在application下新建一个模块,用于执行定时任务的模块,模块名称你可以任意取
第二步,在你新建的模块新建你的定时任务文件 ,Task.php
<?php
namespace app\crontab\command;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Db;
class Task extends Command{
protected function configure()
{
$this->setName('Task')
->setDescription('定时计划测试:每分钟插入一条数据');
}
protected function execute(Input $input, Output $output)
{
// 输出到日志文件
$output->writeln("TestCommand:");
//你的具体要执行的业务逻辑
$this->getTodayOrderCount();
//统计零食订单
$output->writeln("end....");
}
public function getTodayOrderCount(){
编写你要执行的具体业务逻辑
}
}
?>
第三步,在application下的command.php新增你的命令
在里面新增你的定时任务文件。
第四步,使用终端软件链接你的服务器,在你的项目根目录新建定时任务脚本.sh文件,这里我建了一个crontab.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 进入你的项目根目录 # 进入项目的根目录下,保证可以运行php think的命令
php think Task # 执行在Tast.php设定的名
这里有个坑,这个sh脚本千万不要用你自己电脑上的其他编辑器来玩,比如什么notepad++,subline Text等,因为这里有编码问题,最好就直接使用linux自带的vim来写,反正也没几行。
第五步,通过crontab -e指向你的定时脚本,这里对crontab不了解的就自行保底一下crontab吧。
最后,重启一下crontab就可以了。当然要是你觉得使用tp框架麻烦,你也可以自己写一个php脚本来执行,步骤差不多,只是可以不用去按照框架的规则去编写。