[Laravel] Batch processing, Cron task schedule execution
A memorandum of excitement today.
In order to deepen the understanding of batch, I implemented a simple process.
Environment
PHP 7.3.8 Laravel 6.18.35
Write batch processing
Create a batch to get the number of users registered in the User table. First, generate a command class.
php artisan make: command UserCount
When you execute the command, the file is created directly under app / Console / Commands /.
<? php
namespace App \ Console \ Commands;
use Illuminate \ Console \ Command;
// Because there is also a process to output the log later
use Illuminate \ Support \ Facades \ Log;
// Read the table to operate
use App \ User;
class UserCountCommand extends Command
{
/ **
* The name and signature of the console command.
*
* @var string
* /
// Set the name of the command
protected $ signature ='user: count';
/ **
* The console command description.
*
* @var string
* /
// Write the batch description here
protected $ description ='Get number of users';
/ **
* Create a new command instance.
*
* @return void
* /
public function __construct ()
{
parent :: __ construct ();
}
/ **
* Execute the console command.
*
* @return mixed
* /
public function handle ()
{
// Format of message to be output to standard output & log
$ message ='['. date ('Y-m-d h: i: s').'] UserCount:'. User :: count ();
// Output message at INFO level
$ this-> info ($ message);
// Click here for the process of writing the log
Log :: setDefaultDriver ('batch');
Log :: info ($ message);
}
}
This completes the batch
Execute command in terminal
php artisan user: count
If it is displayed like this, it’s OK
Run batches on time with Cron
By describing the entry in crontab, batch processing can be executed regularly according to the contents of the entry.
Reference: Mastering Laravel’s task schedule (cron)
So edit crontab with the vim command.
$ crontab -e
Just add the following line
* * * * * php / path_to_your_project / artisan schedule: run 1 >> / dev / null 2> & 1
Add the created batch command to $ commands
and describe the batch schedule in schedule
.
class Kernel extends ConsoleKernel
{
/ **
* The Artisan commands provided by your application.
*
* @var array
* /
protected $ commands = [
\ App \ Console \ Commands \ UserCountCommand :: class
];;
/ **
* Define the application's command schedule.
*
* @param \ Illuminate \ Console \ Scheduling \ Schedule $ schedule
* @return void
* /
protected function schedule (Schedule $ schedule)
{
// Run the user: count command every minute
$ schedule-> command ('user: count')-> everyMinute ();
}
Looking at the log file
It’s running every minute!