在开发项目的时候使用到了laravel的定时任务,
根据框架文档设置好定时任务后,发现定时任务并没有按预想的执行,
先是检查了环境配置并无异常之处,于是试着在项目文件下执行如下命令
php artisan schedule:run
这个是可以正常运行的,下面总结一下我踩过的坑,跟解决的办法。
错误1
检查PHP proc_open 函数是否开启,宝塔默认是禁用的:
在php.ini中,找到disable_functions选项,看看后面是否有proc_open函数被禁用了,如果有的话,去掉即可.
错误2
复制指令 php /www/wwwroot/atongmu/artisan schedule:run >> /dev/null 2>&1 是确定正常运行的。
后来检查计划任务状态命令如下 :
service crond status
发现是有报错的
crond[2579]: (php) ERROR (getpwnam() failed - user unknown)
错误的重点是,你的/etc/crontab 文件命令有没有用户名,加上就解决了
解决办法:
* * * * * root php /www/wwwroot/atongmu/artisan schedule:run >> /dev/null 2>&1
Laravel框架定时任务执行
1首先我们先创建一个Test.php测试任务
php artisan make:command Test
2.创建完成后会在app/Console/Commands/目录下,如图
3.打开Test.php
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Model\Logs;
class Test extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'test';//命令名称,待会调用php artisan test就会执行
/**
* The console command description.
*
* @var string
*/
protected $description = '这是一条测试任务';//命令描述,没什么用
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();//自构函数,也用不到
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//主要业务逻辑在这些
$tab = new Logs;
$tab->content = ' 测试任务';
$tab->save();
}
}
4.在app/Console/Kernel.php中完成注册。然后要注册这个任务.
5.注册完成后。我们就可以调用这里的任务了,终端中输入如下命令:
php artisan test
数据库中将会添加一条数据
7.然后,我们这里着重说一下定时任务的调度。在app/Console/Kernel.php中还有一个schedule函数,这个就是用来做定时调度的。
方法 描述
->cron(‘* * * * *’); 在自定义Cron调度上运行任务
->everyMinute(); 每分钟运行一次任务
->everyFiveMinutes(); 每五分钟运行一次任务
->everyTenMinutes(); 每十分钟运行一次任务
->everyFifteenMinutes(); 每十五分钟运行一次任务
->everyThirtyMinutes(); 每三十分钟运行一次任务
->hourly(); 每小时运行一次任务
->hourlyAt(17); 每小时第十七分钟运行一次任务
->daily(); 每天凌晨零点运行任务
->dailyAt(‘13:00’); 每天13:00运行任务
->twiceDaily(1, 13); 每天1:00 & 13:00运行任务
->weekly(); 每周运行一次任务
->monthly(); 每月运行一次任务
->monthlyOn(4, ‘15:00’); 每月4号15:00运行一次任务
->quarterly(); 每个季度运行一次
->yearly(); 每年运行一次
->timezone(‘America/New_York’); 设置时区
Laravel定时任务文档:
https://laravelacademy.org/post/8484