Here is an example of Laravel task scheduling. For related methods, please refer to: http://laravelacademy.org/post/8484.html
1. make:command generate task
php artisan make:command MigrateData
After executing the above command, a new Commands directory will be created in the Console directory, which contains a MigrateData.php file
2. Preparation task
Write the logic to be processed in the handle method of MigrateData.php, which is attached below
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class MigrateData extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'data:migrate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'migrate data';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
//Output only one log to see if it is successful
file_put_contents('/home/www/test.log', date("Y-m-d H:i:s") . PHP_EOL, FILE_APPEND);
}
}
3. Modify the Kernel.php file of Console
<?php
namespace App\Console;
use App\Console\Commands\MigrateData;
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 = [
//Add the class name of the new task
\App\Console\Commands\MigrateData::class,
];
/**
* Define the application's command schedule.
*
* @param \Illuminate\Console\Scheduling\Schedule $schedule
* @return void
*/
protected function schedule(Schedule $schedule)
{
// $schedule->command('inspire')
// ->hourly();
// Call with type
$schedule->command(MigrateData::class)->everyMinute();
}
/**
* Register the commands for the application.
*
* @return void
*/
protected function commands()
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}
4. Set cron task
Setting the timing task in crontab-e under linux
/usr/local/php/bin/php /home/www/project/artisan schedule:run >> /dev/null 2>&1
5. remarks
If the execution is not successful, you can directly execute / usr / local / PHP / bin / PHP / home / www / project / artican schedule: run > > / dev / null 2 > & 1 to see if the schedule is successful. If not, there is a problem with the proof code.
In the beginning, I called through the command, and the result was unsuccessful. $schedule - > command ("migratedata") - > everyminute();
Later, the call to the class name succeeded in $schedule - > command (migratedata:: class) - > everyminute();