Master Laravel Scheduled Tasks: From Command Creation to Cron Integration
Learn how to create, configure, and register custom Laravel commands for scheduled tasks, edit the command class, add it to the kernel, define cron timing, and integrate the Laravel scheduler with the system crontab to run automatically every minute.
Basic Usage
Scheduled tasks are a common requirement in backend development, often used for data aggregation, cleaning spam, etc. Laravel provides a complete scheduling toolset so you can focus on business logic while the framework handles the underlying work.
Generate Command
php artisan make:command AreYouOKIn Laravel 5.2 and earlier the command was generated with php artisan make:console xxx.
Edit Command
Edit the file app/Console/Commands/AreYouOK.php and adjust the following parts:
protected $signature = 'areyou:ok'; // command name
protected $description = '雷军,科技圈最会唱歌的男人'; // description (optional)
public function __construct()
{
parent::__construct();
// initialization code (optional)
}
public function handle()
{
// place your task logic here
}Register Command
Add the newly created class to the command list in app/Console/Kernel.php:
protected $commands = [
\App\Console\Commands\AreYouOK::class,
];Define Scheduling Logic
Within the schedule method of the kernel, specify how often the command should run:
protected function schedule(Schedule $schedule)
{
$schedule->command('areyou:ok')
->timezone('Asia/Shanghai')
->everyMinute();
}Laravel offers a variety of timing methods ranging from one minute to one year; you can call the appropriate one directly.
Register Laravel Scheduler with System Cron
Edit the system /etc/crontab file and add the following line (replace /var/www/xxxlaravel with your actual project path):
* * * * * root /usr/bin/php /var/www/xxxlaravel/artisan schedule:run >> /dev/null 2>&1After updating the crontab, restart the cron service to activate the schedule: systemctl restart crond.service That’s the complete guide; feel free to explore further documentation as needed.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
