Laravel Task Scheduling: Cron Jobs Made Easy
Sooner or later someone asks why the weekly digest didn't go out, and you SSH into the box to find a crontab nobody has touched in two years, pointing at a script that was renamed last spring. Cron entries live on the server, not in the repo, so they drift. New servers get provisioned without them, and nobody reviews them in a pull request.
Laravel's scheduler fixes that by moving the schedule into PHP. You add one cron line per server and define everything else in code. This post covers defining tasks, frequencies and constraints, overlap protection, output and alerting, running it in production, and testing.
The schedule lives in app/Console/Kernel.php (or routes/console.php on Laravel 11+), so it goes through code review, ships with deploys, and you can run it locally without touching the server's crontab.
How the Laravel Scheduler Works
A single system cron job runs schedule:run every minute. Laravel checks which of your tasks are due right now and runs them inside the framework, so they have your models, services, queues, and config available.
Laravel Scheduler: one cron entry, unlimited scheduled tasks
The only cron entry you ever need to add to your server is:
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
Everything else is defined in PHP, using chainable methods instead of cron syntax.
Cron runs with a tiny PATH (often just /usr/bin:/bin), so a php binary installed elsewhere, or a specific version like php8.3, may not be found. Because the line pipes everything to /dev/null, you never see the "command not found" error. If tasks silently never fire, use the full path from which php in the crontab line, and temporarily redirect output to a file instead of /dev/null to see what's going on.
Defining Your First Scheduled Task
In Laravel 10 and earlier, tasks go in the schedule method of app/Console/Kernel.php. Laravel 11 dropped the console kernel and you define them in routes/console.php with the Schedule facade instead, but the chained methods are the same. You can schedule an Artisan command, a shell command, or a PHP closure.
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
protected function schedule(Schedule $schedule): void
{
// Run an Artisan command
$schedule->command('emails:send-digest')->daily();
// Run a shell command
$schedule->exec('node /home/app/scripts/sync.js')->hourly();
// Run a PHP closure
$schedule->call(function () {
\DB::table('activity_log')
->where('created_at', '<', now()->subDays(30))
->delete();
})->weekly();
// Run an invokable class
$schedule->call(new GenerateMonthlyReport)->monthlyOn(1, '08:00');
}
}
Creating a Custom Artisan Command to Schedule
I put almost every scheduled task in its own Artisan command. You can test it in isolation, it has a name that shows up in schedule:list, and you can run it by hand when something goes wrong.
Generate the command
Use Artisan's make:command to scaffold a new command class with the correct structure.
php artisan make:command SendWeeklyDigest
Implement the command logic
Define the signature, description, and the handle() method that performs the actual work.
<?php
namespace App\Console\Commands;
use App\Models\User;
use App\Mail\WeeklyDigest;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
class SendWeeklyDigest extends Command
{
protected $signature = 'emails:send-digest
{--dry-run : Preview recipients without sending}';
protected $description = 'Send weekly digest emails to all active subscribers';
public function handle(): int
{
$users = User::where('subscribed', true)
->where('active', true)
->get();
if ($this->option('dry-run')) {
$this->info("Would send to {$users->count()} users.");
return self::SUCCESS;
}
$bar = $this->output->createProgressBar($users->count());
foreach ($users as $user) {
Mail::to($user)->queue(new WeeklyDigest($user));
$bar->advance();
}
$bar->finish();
$this->newLine();
$this->info("Digest queued for {$users->count()} subscribers.");
return self::SUCCESS;
}
}
Register it in the scheduler
Add the command to Kernel.php with your desired frequency.
$schedule->command('emails:send-digest')
->weeklyOn(1, '08:00') // Every Monday at 8:00 AM
->timezone('America/New_York')
->withoutOverlapping()
->onSuccess(function () {
Log::info('Weekly digest sent successfully.');
});
Scheduling Frequencies
There are frequency methods for everything from once a minute to once a year. These are the ones I reach for most:
| Method | Frequency | Cron Equivalent |
|---|---|---|
->everyMinute() |
Every minute | * * * * * |
->everyFiveMinutes() |
Every 5 minutes | */5 * * * * |
->everyThirtyMinutes() |
Every 30 minutes | 0,30 * * * * |
->hourly() |
Every hour at :00 | 0 * * * * |
->hourlyAt(17) |
Every hour at :17 | 17 * * * * |
->daily() |
Daily at midnight | 0 0 * * * |
->dailyAt('13:00') |
Daily at 1:00 PM | 0 13 * * * |
->weeklyOn(1, '08:00') |
Monday at 8:00 AM | 0 8 * * 1 |
->monthly() |
1st of month at midnight | 0 0 1 * * |
->monthlyOn(15, '10:00') |
15th of month at 10 AM | 0 10 15 * * |
->quarterly() |
First day of each quarter | 0 0 1 1-12/3 * |
->yearly() |
January 1st at midnight | 0 0 1 1 * |
->cron('30 9 * * 1-5') |
Custom cron expression | Weekdays at 9:30 AM |
Conditional Scheduling with Constraints
Some tasks should only run on weekdays, only when a feature flag is on, or only in production. when(), skip() and a few helpers cover those cases:
// Only run on weekdays
$schedule->command('reports:generate')
->daily()
->weekdays();
// Only run when a condition is true
$schedule->command('sync:external-data')
->hourly()
->when(fn() => config('features.external_sync_enabled'));
// Skip when condition is true
$schedule->command('cache:warm')
->everyFiveMinutes()
->skip(fn() => app()->isDownForMaintenance());
// Only run between 6 AM and 10 PM
$schedule->command('notifications:send-push')
->everyFifteenMinutes()
->between('06:00', '22:00');
// Run on specific environments
$schedule->command('analytics:process')
->daily()
->environments(['production']);
By default, scheduled tasks run in your application's timezone. You can override this per task with ->timezone('Europe/London'), which matters for things like morning reports that should go out at local time. Watch out for daylight saving: a task scheduled between 1 and 3 AM in a DST timezone can run twice or not at all on the changeover nights, so keep those in UTC.
Preventing Task Overlap
Here's a problem that only shows up once real data arrives: a task takes longer than its interval. An import scheduled every five minutes takes seven, the next run starts while the first is still going, and now you have duplicate rows or deadlocks. withoutOverlapping() stops this by taking a cache lock before the task runs and skipping the run if the lock is held.
// Default: mutex expires after 24 hours if task crashes
$schedule->command('import:products')
->everyFiveMinutes()
->withoutOverlapping();
// Custom expiry: release mutex after 10 minutes
$schedule->command('import:products')
->everyFiveMinutes()
->withoutOverlapping(10);
// Run in the background (non-blocking for the scheduler process)
$schedule->command('reports:generate-all')
->daily()
->runInBackground();
// Combine: background + no overlap
$schedule->command('sync:inventory')
->everyMinute()
->withoutOverlapping()
->runInBackground();
The lock is stored in your cache. A file cache only works on a single server, and array doesn't persist between runs at all. With several servers, use a shared store such as Redis, Memcached, DynamoDB or the database driver. Also, if the process is killed mid-run (OOM, deploy restart), the lock stays until it expires, which is 24 hours by default. If a task suddenly stops running after a crash, php artisan schedule:clear-cache clears the stale locks.
withoutOverlapping() skips a run while the previous one still holds the lock
Output Handling
By default, scheduled commands throw their output away. That's fine until a job fails at 2 AM and you have nothing to look at. You can write output to a file, email it, ping a monitoring service, or hook into success and failure.
// Overwrite log file each run
$schedule->command('import:products')
->daily()
->sendOutputTo(storage_path('logs/import.log'));
// Append to existing log file
$schedule->command('import:products')
->daily()
->appendOutputTo(storage_path('logs/import.log'));
// Combine stderr and stdout
$schedule->exec('backup.sh')
->daily()
->appendOutputTo(storage_path('logs/backup.log'));
// Email output only when there's content (errors/warnings)
$schedule->command('cleanup:temp-files')
->daily()
->emailWrittenOutputTo('admin@example.com');
// Always email output, even when empty
$schedule->command('reports:generate')
->monthly()
->emailOutputTo('manager@example.com');
// Email to multiple recipients
$schedule->command('inventory:sync')
->daily()
->emailWrittenOutputTo([
'devops@example.com',
'support@example.com',
]);
// Ping a URL when the task starts (e.g., Healthchecks.io)
$schedule->command('backup:run')
->daily()
->pingBefore('https://hc-ping.com/YOUR-UUID/start')
->thenPing('https://hc-ping.com/YOUR-UUID');
// Ping only on success
$schedule->command('sync:data')
->hourly()
->thenPingIf(true, 'https://hc-ping.com/YOUR-UUID');
// Ping on failure
$schedule->command('reports:generate')
->daily()
->pingOnFailure('https://hc-ping.com/YOUR-UUID/fail');
$schedule->command('emails:send-digest')
->weekly()
->before(function () {
Log::info('Starting weekly digest run');
})
->after(function () {
Log::info('Weekly digest run complete');
})
->onSuccess(function (Stringable $output) {
// $output contains command stdout
Cache::put('last_digest_output', $output, 3600);
})
->onFailure(function (Stringable $output) {
// Alert the team
Notification::route('mail', 'devops@example.com')
->notify(new SchedulerFailedAlert($output));
});
Real-World Scheduling Patterns
Database Cleanup Jobs
Tables like activity logs and password resets grow forever unless something trims them. A daily prune command keeps them in check.
<?php
namespace App\Console\Commands;
use App\Models\PasswordReset;
use App\Models\PersonalAccessToken;
use App\Models\ActivityLog;
use Illuminate\Console\Command;
class PruneExpiredData extends Command
{
protected $signature = 'db:prune-expired';
protected $description = 'Remove expired tokens, resets, and old activity logs';
public function handle(): int
{
$deleted = 0;
// Expired password resets (older than 60 minutes)
$deleted += PasswordReset::where('created_at', '<', now()->subHour())->delete();
// Expired personal access tokens
$deleted += PersonalAccessToken::where('expires_at', '<', now())->delete();
// Activity logs older than 90 days
$deleted += ActivityLog::where('created_at', '<', now()->subDays(90))->delete();
$this->info("Pruned {$deleted} records.");
return self::SUCCESS;
}
}
// In Kernel.php
$schedule->command('db:prune-expired')
->daily()
->withoutOverlapping()
->appendOutputTo(storage_path('logs/pruning.log'));
Nightly Report Generation
Heavy reports go in a quiet hour, in the background, with a failure hook so you hear about it. One note on the sitemap example: Google has since retired its sitemap ping endpoint, so in a real app submit the sitemap through Search Console or list it in robots.txt instead.
// In Kernel.php schedule()
$schedule->command('reports:daily-sales')
->dailyAt('02:00') // Run at 2 AM
->timezone('UTC')
->withoutOverlapping()
->runInBackground()
->onFailure(function () {
// Alert Slack or email
Log::critical('Daily sales report generation failed!');
});
$schedule->command('reports:generate-sitemap')
->weekly()
->onSuccess(function () {
// Ping Google to re-crawl
Http::get('https://www.google.com/ping?sitemap='
. urlencode(config('app.url') . '/sitemap.xml'));
});
Queue Health Monitoring
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Queue;
class MonitorQueueHealth extends Command
{
protected $signature = 'queue:health-check
{--threshold=1000 : Alert if more than N jobs are waiting}';
protected $description = 'Alert when the default queue has too many pending jobs';
public function handle(): int
{
$size = Queue::size('default');
$threshold = (int) $this->option('threshold');
if ($size > $threshold) {
$this->error("ALERT: Queue has {$size} jobs (threshold: {$threshold})");
return self::FAILURE;
}
$this->info("Queue healthy: {$size} jobs pending.");
return self::SUCCESS;
}
}
// In Kernel.php
$schedule->command('queue:health-check --threshold=500')
->everyFiveMinutes()
->emailWrittenOutputTo('devops@example.com'); // Only emails on FAILURE output
Running the Scheduler in Production
Setting Up the System Cron
Add the cron entry for the same user that runs PHP-FPM. If you add it to root's crontab, the first scheduled run creates files in storage/logs owned by root, and then your web requests start failing with "Permission denied" when they try to write to the same log.
# Open crontab as the user that runs PHP (e.g., www-data or forge)
sudo -u www-data crontab -e
# Add this single line
* * * * * cd /var/www/your-app && php artisan schedule:run >> /dev/null 2>&1
# Verify crontab was saved
sudo -u www-data crontab -l
Using Laravel Scheduler with Supervisor (Daemon Mode)
Since Laravel 8 there's also schedule:work, a long-running process that calls the scheduler every minute, so you don't need a system cron at all. It's handy locally and on platforms (some PaaS hosts, containers) where you can't edit a crontab. On a regular VPS I'd still use cron, since it's one less process to keep alive.
[program:laravel-scheduler]
process_name=%(program_name)s
command=php /var/www/your-app/artisan schedule:work
autostart=true
autorestart=true
user=www-data
redirect_stderr=true
stdout_logfile=/var/log/supervisor/scheduler.log
stopwaitsecs=60
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start laravel-scheduler:*
sudo supervisorctl status
Listing All Scheduled Tasks
Use the built-in schedule:list command to see every registered task, its next run time, and its cron expression. It's the first thing I run when someone says a job didn't fire.
php artisan schedule:list
# Output example:
# Command Interval Next Due
# emails:send-digest Weekly 2026-05-04 08:00:00
# db:prune-expired Daily 2026-05-02 00:00:00
# reports:daily-sales Daily 2026-05-02 02:00:00
# queue:health-check --threshold Every 5m 2026-05-01 12:05:00
# Run a specific task immediately (bypassing schedule)
php artisan schedule:run --verbose
Testing Scheduled Tasks
Scheduled tasks tend to go untested because nobody wants to wait for 2 AM. Split it in two: check that the task is registered on the Schedule, and test the command itself with $this->artisan().
<?php
namespace Tests\Feature;
use Illuminate\Console\Scheduling\Schedule;
use Tests\TestCase;
class SchedulerTest extends TestCase
{
public function test_digest_command_is_scheduled_weekly(): void
{
$schedule = app(Schedule::class);
$events = collect($schedule->events())
->filter(fn($event) => str_contains($event->command, 'emails:send-digest'));
$this->assertCount(1, $events, 'send-digest should be scheduled exactly once');
$event = $events->first();
$this->assertTrue($event->isDue(app()), 'Task should be due now for testing');
}
public function test_digest_command_executes_successfully(): void
{
// Test the command itself in isolation
$this->artisan('emails:send-digest --dry-run')
->assertExitCode(0)
->expectsOutputToContain('Would send to');
}
public function test_prune_command_deletes_old_records(): void
{
// Create records that should be deleted
ActivityLog::factory()->count(5)->create([
'created_at' => now()->subDays(100),
]);
$this->artisan('db:prune-expired')->assertExitCode(0);
$this->assertDatabaseCount('activity_logs', 0);
}
}
Scheduler vs Queue Workers: When to Use Each
| Criteria | Task Scheduler | Queue Worker |
|---|---|---|
| Trigger | Time-based (cron) | Event-based (job dispatched) |
| Example | Nightly report at 2 AM | Send email after registration |
| Retries | Not automatic; just runs again next cycle | Configurable automatic retries |
| Concurrency | Use withoutOverlapping() | Multiple workers by default |
| Monitoring | schedule:list, log output | Horizon dashboard, queue:monitor |
| Best for | Batch operations, maintenance, reports | User-triggered async work, notifications |
Often used together: the scheduler fires a command that dispatches queue jobs, so you get time-based triggering plus the queue's retries and parallel workers.
What to check before going to production
Before the first deploy
- Multiple servers: if every app server has the cron line, every task runs on every server. Add
onOneServer()to tasks that must run once, and make sure the cache is shared (Redis, Memcached, database), or the lock does nothing. - Long tasks block the rest: tasks due in the same minute run one after another. A 20 minute report without
runInBackground()delays everything queued behind it. - Silent failures: the crontab sends output to
/dev/null. WithoutonFailure(), a heartbeat ping, or a log file, a broken job can go unnoticed for weeks. - Deploys: run
php artisan schedule:listafter deploying to confirm what's registered, and remember that a deploy that kills a running task can leave a stale overlap lock behind.
I'd use the scheduler for anything time-based that belongs to the app: cleanups, reports, syncs, digests. I wouldn't use it as a replacement for a queue. If the work is triggered by a user action, or needs retries and fan-out, dispatch a job. I also wouldn't schedule something every minute that does heavy work inline; have the scheduled command dispatch queue jobs and let the workers do the lifting.
And if the job has nothing to do with Laravel, like rotating server logs or renewing certificates, leave it in plain cron or a systemd timer. Booting the framework every minute for that buys you nothing.