Using Closures and Artisan Commands for Scheduled Tasks
Scheduled tasks in Laravel aren't limited to full Artisan commands. Simple, one-off logic can be scheduled directly as a closure, without creating a dedicated command class at all.
Scheduling a Closure
$schedule->call(function () {
DB::table('recent_visits')->delete();
})->daily();
This is convenient for small maintenance tasks that don't warrant their own command file.
Scheduling an Artisan Command
$schedule->command('reports:generate --detailed')->dailyAt('01:00');
Artisan commands are the better choice when the task is reusable, needs to be run manually as well, or requires its own arguments and options.
Combining Constraints
$schedule->command('emails:send')
->daily()
->weekdays()
->withoutOverlapping();
withoutOverlapping() is particularly useful for long-running tasks, preventing a new run from starting if the previous one hasn't finished yet.
Choosing Between the Two
- Closures — quick, inline, no reuse needed
- Artisan commands — reusable, testable, callable outside the scheduler too
That wraps up task scheduling and, with it, the full arc of this course — from routing and Blade through Eloquent, authentication, file handling, APIs, events, queues, and now scheduled automation.
Ready to master Laravel Training Course?
Join Uncodemy's hands-on Laravel program and build real, production-ready applications.
