laravel - Laravel 5.5: Want to run multiple cronjobs through kernel.php under App/Console
问题描述
I want to run different cronjobs like deleting users, send coupon codes to users, send greeting to users who joined between specified dates and etc. Can I do the same by opening the App\Console\Kernel.php and write the command as below:
protected $commands = [
'\App\Console\Commands\DeleteUsers',
'\App\Console\Commands\SendCouponCode',
'\App\Console\Commands\SendGreetings',
];
protected function schedule(Schedule $schedule)
{
$schedule->command('DeleteUsers:deleteuserscronjob')->everyMinute();
$schedule->command('SendCouponCode:sendcouponcodecronjob')->everyMinute();
$schedule->command('SendGreetings:sendgreetingscronjob')->everyMinute();
}
Also, can someone suggest how to run cronjobs by calling only the methods under controllers and not by commands, as like below?
App\Http\Controllers\MyController1@MyAction1
And,
App\Http\Controllers\MyController2@MyAction2
解决方案
Using kernel.php to schedule tasks is the correct way to do it according to the Laravel framework.
However, if you want to execute a method in one of your controllers instead of creating a command for it, you can do it like so:
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
MyController::myStaticMethod();
})->daily();
}
For running a schedules task via a command:
protected $commands = [
Commands\MyCommand::class,
];
protected function schedule(Schedule $schedule)
{
$schedule->command('mycommand:run')->withoutOverlapping();
}
Then in app\Console\Commands\MyCommand.php:
namespace App\Console\Commands;
use Illuminate\Console\Command;
use DB;
class MyCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'mycommand:run';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Description of my command';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// PUT YOUR TASK TO BE RUN HERE
}
}
推荐阅读
- javascript - javascript - 在文本框上传递值
- php - 从具有相同列名mysql的两个表中选择
- c++ - 模板而不是接口的缺点是什么?(C++)
- node.js - "message": "无法读取未定义的属性 'query'",
- c++ - 来自 libm 和 libstdc++ 的重复符号
- asp.net - 在 SSMS 中获取 ASP.NET Web API 数据
- javascript - this.innerHTML 不适用于链接?
- django - 一对一关系未在 json 响应中返回嵌套序列化程序
- javascript - 为什么在 JavaScript 中使用一元运算符 ++ 的变量不会将变量更改 1,直到该变量下一次出现在括号内?
- javascript - 如何从 Google Maps API 反向地理编码中显示所需的元素?