tp5.1中的php 计划任务的实现,本质上可以分为两种第一种封装在框架内部,在crontab -e中只要添加一条,然后在框架内去扩展内容就好了(Laravel的schedule
,任务调度),这种自由度比较高,也比较方便。第二种:创建好PHP的执行脚本,在crontab中执行脚本,或者再写一个.sh 在crontab中执行,这种就需要在服务器上去执行一些文件,相对而言,比较麻烦,当然效果还是一样的。
方法1.创建一个php脚本,1.php,创建一个test.sh ,赋予权限 chmod + x test.sh ,其中有个注意点 当时我去执行cd 命令的时候直接报错了,后来原因找到了,是由于你写*.sh的文件 是在windows ,然后在上传到liunx 服务器. windows 的编码格式是docs 而liunx 只能是unix. 解决办法:1. vi test.sh 文件 2.通过 :set ff 你会发现该文件的格式fomat=docs 3. 通过 :set ff=unix 然后 :x或:wq 保存并退出。
#!/bin/bash
# cd /data/wwwroot/default
/usr/bin/php /data/wwwroot/default/1.php
最后在crontab中,一分钟执行一次,输出到log中去,查验效果就可以了。简单自测的方法 直接在test.sh 所在目录直接./test.sh或者是sh test.sh 就可以查看脚本运行结果了
*/1 * * * * sh /data/wwwroot/default/test.sh 2 >>/data/wwwroot/default/log.txt
方法2.利用tp自带的think自定义command 功能,在application/模块/新建一个command文件夹/Crontab.class.php,其中的class可以省略,假如在配置的app.php中关闭了class_suffix,修改文件名为Crontab.php
<?php
namespace app\api\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
class Crontab extends Command
{
protected function configure(){
$this->setName('Crontab')->setDescription("计划任务 Crontab");
}
protected function execute(Input $input, Output $output){
$output->writeln('Date Crontab job start...');
/*** 这里写计划任务列表集 START ***/
$this->test();
/*** 这里写计划任务列表集 END ***/
$output->writeln('Date Crontab job end...');
}
private function test(){
echo "test\r\n";
}
}
配置command.php文件,位置在application/command.php
return ['app\api\command\Crontab'];
打开命令行,运行php think Test命令test命令execute方法中运行的方法就会运行。剩下来的就是写一个Crontab.sh来执行,注意格式
#!/bin/bash
cd /data/wwwroot/default/purenfort-api
/usr/bin/php think Crontab
最后在crontab中,一分钟执行一次,输出到log中去,查验效果就可以了简单自测的方法直接在Crontab.sh所在目录直接 ./Crontab.sh或者是sh Crontab.sh 就可以查看脚本运行结果了 。注意php在shell脚本中要写全路径,注意.sh脚本权限、编码格式问题。其他就没啥了。