How to use Laravel's Task Scheduling
Aug 31, 2025 am 06:07 AMLaravel's Task Scheduling system allows you to define and manage timing tasks through PHP, without manually editing the server crontab, you only need to add a cron task that is executed once a minute to the server: * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1, and then all tasks are configured in the schedule method of the App\Console\Kernel class; 1. Defining tasks can use command, call or exec methods, such as $schedule->command('emails:send')->daily() to achieve daily email sending; 2. Supports a variety of scheduling options, such as ->everyFiveMinutes(), ->dailyAt('10:00'), ->weekly(), ->weekdays() and ->timezone('America/New_York'), etc. to precisely control the execution time; 3. Use ->withoutOverlapping() to prevent tasks from overlapping execution, and combine ->onOneServer() to ensure that it only runs once in a multi-server environment, and depends on Redis or database cache driver support; 4. You can write the output to the log file through ->sendOutputTo() or ->appendOutputTo(), and use ->emailOutputOnFailure('admin@example.com') to send email notifications when failure; 5. You can use php artisan schedule:run manually triggers scheduler execution, or use php artisan schedule:list to view defined tasks list to verify configuration correctness, thereby achieving centralized, easy-to-maintain scheduled task management.
Laravel's Task Scheduling system allows you to define and manage cron jobs directly in PHP, making it easier to automate recurring tasks like cleaning up logs, sending emails, or syncing data. Instead of manually editing the server's crontab, Laravel provides a clean, expressive syntax to define scheduled tasks in your application.
Here's how to use Laravel's Task Scheduling effectively.
1. Setting Up the Scheduler
To get started, you only need to add one cron entry on your server. This single cron job calls Laravel's scheduler every minute, which then checks if any scheduled tasks should run.
Add this line to your server's crontab (use crontab -e
to edit):
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Replace /path-to-your-project
with the actual path to your Laravel application.
Once this is set up, all your scheduled tasks will be managed from within Laravel, specifically in the App\Console\Kernel
class.
2. Defining Scheduled Tasks
Open the app/Console/Kernel.php
file. Inside the schedule
method, you can define all your recurring commands.
For example, let's schedule an artisan command to run daily:
protected function schedule(Schedule $schedule) { $schedule->command('emails:send')->daily(); }
You can also schedule closings:
$schedule->call(function () { // Clear cache or perform cleanup \Cache::flush(); })->hourly();
Or run shell commands:
$schedule->exec('rm /tmp/*.tmp')->daily();
3. Common Scheduling Options
Laravel provides many methods to control when a task runs. Here are some of the most useful:
-
->everyFiveMinutes()
– Runs every 5 minutes -
->hourly()
– Once per hour -
->daily()
– Once per day at midnight -
->dailyAt('10:00')
– Every day at 10 AM -
->weekly()
– Once per week (Sunday at 00:00) -
->monthly()
– Once per month -
->weekdays()
– Only on weekdays -
->timezone('America/New_York')
– Set a specific timezone
Example combining multiple constraints:
$schedule->command('backup:run') ->daily() ->at('02:30') ->timezone('Europe/London') ->onOneServer(); // Prevents overlapping on multiple servers
4. Preventing Overlapping and Ensuring Single Server Execution
If a task takes longer than expected, it might overlap with the next run. To avoid this, use:
$schedule->command('long:task')->daily()->withoutOverlapping();
When running on multiple servers (eg, load-balanced), use onOneServer()
to ensure the task runs only once across the cluster:
$schedule->command('sync:feeds')->hourly()->onOneServer();
This requires your application to use a cache driver that supports atomic locks (like Redis or database).
5. Output and Logging
You can save the output of scheduled commands to a file or log it:
$schedule->command('emails:send') ->daily() ->sendOutputTo(storage_path('logs/email-schedule.log'));
Or append output and errors:
$schedule->command('emails:send') ->daily() ->appendOutputTo(storage_path('logs/email-schedule.log'));
You can also email output if something goes wrong (useful for monitoring):
$schedule->command('emails:send') ->daily() ->emailOutputOnFailure('admin@example.com');
Make sure your mail settings are configured.
6. Testing Scheduled Tasks
To manually test if your schedule runs correctly, use:
php artisan schedule:run
This command runs Laravel's scheduler, which checks all defined tasks and executes any due ones.
You can also list all scheduled jobs (Laravel 9):
php artisan schedule:list
This helps verify your syntax and timing.
Basically, Laravel's task scheduling simplifies cron job management by centralizing it in PHP. As long as the main cron entry is set up, you can define, tweak, and monitor all recurring tasks directly in your code.
The above is the detailed content of How to use Laravel's Task Scheduling. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Create models and migration: Use phpartisanmake:modelPost-m to generate models and migration files, define the table structure and run phpartisanmigrate; 2. Basic CRUD operations: use Post::all(), find(), create(), save() and delete() methods to query, create, update and delete data; 3. Use Eloquent association: define belongsTo and hasMany relationships in the model, and use the with() method to preload the associated data to avoid N 1 query problems; 4. Eloquent query: use query constructor to chain calls such as where

PolymorphicrelationshipsinLaravelallowamodellikeCommentorImagetobelongtomultiplemodelssuchasPost,Video,orUserusingasingleassociation.2.Thedatabaseschemarequires{relation}_idand{relation}_typecolumns,exemplifiedbycommentable_idandcommentable_typeinaco

Yes,youcancreateasocialnetworkwithLaravelbyfollowingthesesteps:1.SetupLaravelusingComposer,configurethe.envfile,enableauthenticationviaBreeze/Jetstream/Fortify,andrunmigrationsforusermanagement.2.Implementcorefeaturesincludinguserprofileswithavatarsa

Laravel's TaskScheduling system allows you to define and manage timing tasks through PHP, without manually editing the server crontab, you only need to add a cron task that is executed once a minute to the server: *cd/path-to-your-project&&phpartisanschedule:run>>/dev/null2>&1, and then all tasks are configured in the schedule method of the App\Console\Kernel class; 1. Defining tasks can use command, call or exec methods, such as $schedule-

Create language files: Create subdirectories for each language (such as en, es) in the resources/lang directory and add messages.php file, or use JSON file to store translation; 2. Set application language: read the request header Accept-Language through middleware or detect language through URL prefix, set the current language using app()->setLocale(), and register the middleware in Kernel.php; 3. Use translation functions: use __(), trans() or @lang in the view, and use __() that supports fallback; 4. Support parameters and plural: Use placeholders in translation strings such as: n

Using Laravel to build a mobile backend requires first installing the framework and configuring the database environment; 2. Define API routes in routes/api.php and return a JSON response using the resource controller; 3. Implement API authentication through LaravelSanctum to generate tokens for mobile storage and authentication; 4. Verify file type when uploading files and store it on public disk, and create soft links for external access; 5. The production environment requires HTTPS, set current limits, configure CORS, perform API version control and optimize error handling. It is also recommended to use API resources, paging, queues and API document tools to improve maintainability and performance. Use Laravel to build a safe,

LaravelusesMonologtologmessagesviatheLogfacade,withdefaultlogsstoredinstorage/logs/laravel.log.Configurechannelsinconfig/logging.phptocontroloutput;thedefaultstackchannelaggregatesmultiplehandlerslikesingle,whichwritestoafile.UseLog::info(),Log::warn

Ensure that there is a remember_token column in the user table. Laravel's default migration already includes this field. If not, it will be added through migration; 2. Add a check box with name remember in the login form to provide the "Remember Me" option; 3. Pass the remember parameter to the Auth::attempt() method during manual authentication to enable persistent login; 4. "Remember Me" lasts for 5 years by default, and can be customized through the remember_for configuration item in config/auth.php; 5. Laravel automatically invalidates remember_token when password changes or user deletes. It is recommended to use HTTPS to ensure security in the production environment; 6
