Mastering Laravel 12 Scheduler: Automate Your Tasks Like a Pro

Author

Kritim Yantra

Jun 14, 2025

Mastering Laravel 12 Scheduler: Automate Your Tasks Like a Pro

Have you ever forgotten to back up your database? Or struggled to send emails in batches without manual oversight? These tasks—backup, cleanup, email dispatch—are perfect candidates for automation. Traditionally, you’d write separate cron jobs on your server for each task. But managing numerous crons across environments is painful.

Laravel’s Task Scheduler solves this beautifully. It offers a fluent, expressive API that lets you define all scheduled tasks in code. You get version control, easy deployment, and centralized management—all with one simple cron entry.


✨ Getting Started with Laravel Scheduler

In Laravel 12, scheduled tasks live in routes/console.php.

Here’s a simple example:

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schedule;

Schedule::call(function () {
    DB::table('recent_users')->delete();
})->daily();

You can also use invokable classes:

Schedule::call(new DeleteRecentUsers)->daily();

To list all scheduled entries:

php artisan schedule:list

️ Scheduling Artisan Commands

Laravel makes it easy to schedule Artisan commands:

Schedule::command('emails:send Taylor --force')->daily();

Or using the command class:

Schedule::command(SendEmailsCommand::class, ['Taylor','--force'])->daily();

You can also define the schedule inline:

Artisan::command('emails:send {user} {--force}', function ($user) {
    // Logic here
})->purpose('Send emails to the user')
  ->schedule(['Taylor', '--force'])
  ->daily();

🚗 Scheduling Jobs

If you’re using queued jobs, Laravel lets you schedule them easily:

Schedule::job(new Heartbeat)->everyFiveMinutes();

Specify queue and connection:

Schedule::job(new Heartbeat, 'heartbeats', 'sqs')->everyFiveMinutes();

⌛ Scheduling Shell Commands

Laravel also supports shell commands:

Schedule::exec('node /home/forge/script.js')->daily();

🕒 Flexible Frequency Options

Laravel offers built-in timing methods:

  • ->everyMinute()
  • ->hourly()
  • ->daily()
  • ->weekly()
  • ->monthlyOn(4, '15:00')
  • ->lastDayOfMonth('15:00')
  • ->quarterly()
  • ->yearlyOn(6, 1, '17:00')

You can also use raw cron syntax:

->cron('* * * * *')

🧰 Conditional Scheduling

Laravel supports powerful conditions:

  • Days: .weekdays(), .mondays(), .days([1, 2])
  • Time: .between('9:00', '17:00'), .unlessBetween('23:00', '4:00')
  • Logic: .when(fn() => true), .skip(fn() => false)
  • Environments: .environments(['production'])

🌐 Timezones

Control task timing with timezones:

Schedule::command('report:generate')
  ->timezone('America/New_York')
  ->at('2:00');

Global setting in config/app.php:

'schedule_timezone' => 'America/Chicago'

🏛 Preventing Overlaps

Ensure only one task runs at a time:

Schedule::command('emails:send')->withoutOverlapping();

Optionally specify lock expiry:

->withoutOverlapping(10); // 10 minutes

Clear stuck tasks:

php artisan schedule:clear-cache

🚨 Run Once on One Server

In multi-server setups:

Schedule::command('report:generate')
  ->fridays()->at('17:00')->onOneServer();

Give unique names for similar tasks:

Schedule::job(new CheckUptime('https://laravel.com'))
  ->name('check_uptime:laravel.com')
  ->everyFiveMinutes()
  ->onOneServer();

💡 Run in the Background

Prevent blocking:

Schedule::command('analytics:report')->daily()->runInBackground();

🏠 Maintenance Mode Handling

Let tasks run during maintenance:

Schedule::command('emails:send')->evenInMaintenanceMode();

📅 Grouping Tasks

Group related tasks with shared settings:

Schedule::daily()
  ->onOneServer()
  ->timezone('America/New_York')
  ->group(function () {
      Schedule::command('emails:send --force');
      Schedule::command('emails:prune');
  });

📲 Setting Up the Scheduler

Add one cron to your server:

* * * * * cd /path && php artisan schedule:run >> /dev/null 2>&1

⌛ Sub-Minute Tasks

Laravel supports every-second tasks:

Schedule::call(fn() => ...)->everySecond();

Use schedule:interrupt for graceful shutdowns:

php artisan schedule:interrupt

🎨 Output Handling

  • sendOutputTo($filePath)
  • appendOutputTo($filePath)
  • emailOutputTo('[email protected]')
  • emailOutputOnFailure('[email protected]')

🚀 Task Lifecycle Hooks

  • .before(fn() => ...)
  • .after(fn() => ...)
  • .onSuccess(fn() => ...)
  • .onFailure(fn() => ...)

Access output using Stringable $output.


📡 Ping URLs for Monitoring

Notify services:

->pingBefore($url)
->thenPing($url)
->pingOnSuccess($url)
->pingOnFailure($url)

🎓 Event Listening

Laravel fires events:

  • ScheduledTaskStarting
  • ScheduledTaskFinished
  • ScheduledTaskSkipped
  • ScheduledTaskFailed
  • ScheduledBackgroundTaskFinished

🧠 Final Thoughts

Laravel’s scheduler is a developer-friendly system for automating background tasks. Whether you're cleaning tables, running jobs every minute, or coordinating cron scripts, it makes your life easier.

Key Takeaways

  • Define schedules in code
  • Use one cron job
  • Schedule everything: closures, commands, jobs, shell commands
  • Powerful timing and constraints
  • Prevent overlaps, run in background, monitor with hooks

Try scheduling a task in your Laravel project today. It’s one of those features that feels magical once you start using it!

LIVE MENTORSHIP ONLY 5 SPOTS

Laravel Mastery
Coaching Class Program

KritiMyantra

Transform from beginner to Laravel expert with our personalized Coaching Class starting June 26, 2025. Limited enrollment ensures focused attention.

Daily Sessions

1-hour personalized coaching

Real Projects

Build portfolio applications

Best Practices

Industry-standard techniques

Career Support

Interview prep & job guidance

Total Investment
$200
Duration
30 hours
1h/day

Enrollment Closes In

Days
Hours
Minutes
Seconds
Spots Available 5 of 10 remaining
Next cohort starts:
June 26, 2025

Join the Program

Complete your application to secure your spot

Application Submitted!

Thank you for your interest in our Laravel mentorship program. We'll contact you within 24 hours with next steps.

What happens next?

  • Confirmation email with program details
  • WhatsApp message from our team
  • Onboarding call to discuss your goals

Tags

Comments

No comments yet. Be the first to comment!

Please log in to post a comment:

Sign in with Google

Related Posts