Master Laravel Scheduled Tasks: From Command Creation to System Cron
This guide walks you through creating a Laravel Artisan command, editing its signature and logic, registering it in the kernel, defining a schedule using Laravel's fluent scheduler, and finally integrating the task with the system crontab for automatic execution.
Scheduled tasks are a common backend requirement for data aggregation, cleanup, and similar scenarios, and Laravel provides a full-featured scheduler that lets you focus on business logic.
Generating a Command
<code>php artisan make:command AreYouOK</code>In Laravel 5.2 and earlier the command is created with php artisan make:console xxx .
Editing the Command
Open app/Console/Commands/AreYouOK.php and set the signature and description, then implement the constructor and handle method.
<code>protected $signature = 'areyou:ok'; // command name
protected $description = '雷军,科技圈最会唱歌的男人'; // description
public function __construct()
{
parent::__construct();
// initialization code
}
public function handle()
{
// task logic here
}</code>Registering the Command
Add the command class to the $commands array in app/Console/Kernel.php :
<code>protected $commands = [
\App\Console\Commands\AreYouOK::class,
];</code>Defining the Schedule
In the schedule method of Kernel.php , schedule the command to run every minute (or any interval supported by Laravel):
<code>protected function schedule(Schedule $schedule)
{
$schedule->command('areyou:ok')
->timezone('Asia/Shanghai')
->everyMinute();
}</code>Laravel offers time‑based methods ranging from minutes to years.
Adding Laravel to System Cron
Append the following line to /etc/crontab (replace /var/www/xxxlaravel with your actual project path):
<code>* * * * * root /usr/bin/php /var/www/xxxlaravel/artisan schedule:run >> /dev/null 2>&1</code>Restart the cron service to activate the schedule:
<code>systemctl restart crond.service</code>Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.