宝塔面板+laravel5.2 添加定时任务
程序员文章站
2022-07-08 11:10:07
...
1、laravel添加定时任务
文档:https://xueyuanjun.com/post/3267
1.1配置console的Kernel
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* The Artisan commands provided by your application.
*
* @var array
*/
protected $commands = [
Commands\SettleAccounts::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
$schedule->command('SettleAccounts')->withoutOverlapping();
}
}
1.2新建command脚本
新建目录App\Console\Commands
在Commands目录下新建SettleAccounts类
<?php
namespace App\Console\Commands;
use App\Models\Site\PunchProject;
use App\Models\Site\Regular;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
class SettleAccounts extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'SettleAccounts';
/**
* The console command description.
*
* @var string
*/
protected $description = '定时任务发放奖励';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
const HAS_FAILED = 'HasFailed'; //已执行打卡失败
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//任务逻辑 TODO
$this->kernel_log('定时任务发放奖励 ===begin====');
$this->kernel_log('定时任务发放奖励 $getList' . json_encode($getList));
$this->kernel_log('定时任务发放奖励 ===end====');
// Log::info('定时任务发放奖励 ===end====');
}
public function kernel_log($msg){
//一定加$monolog这两句,不然会打印两份日志
$monolog = Log::getMonolog();
$monolog->popHandler();
//Log::useDailyFiles(storage_path('logs/error/test.log'));
// Log::useFiles(storage_path('logs/kernel_log/kernel.log'));
Log::useDailyFiles(storage_path('logs/kernel_log/kernel.log'));
// Log::emergency("系统挂掉了");
// Log::alert("数据库访问异常");
// Log::critical("系统出现未知错误");
// Log::error("指定变量不存在");
// Log::warning("该方法已经被废弃");
// Log::notice("用户在异地登录");
Log::info($msg);
// Log::debug("调试信息");
}
}
2、宝塔面板添加定时任务
脚本内容 xxx.com为网址域名
php /www/wwwroot/xxx.com/artisan schedule:run
注意,这里有个坑
如果在执行脚本PHP文件里写了日志,需要注意。
宝塔面板执行计划任务生成的日志 是 root 权限的,laravel程序生成的日志,权限是www。
执行定时任务之后,再遇到其他写日志的地方,会报500错误。
我的解决办法是:自定义一个文件夹存储定时任务生成的日志,方法已写到上边的文件里
参考文档:
https://www.cnblogs.com/johnson108178/p/8023972.html
https://blog.csdn.net/woqianduo/article/details/83995093
下一篇: python火车票爬虫