Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

Subscribe to the newsletter

Get new articles and course lessons delivered to your inbox. No spam, unsubscribe anytime.

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 33 of the Intermediate Laravel: Real-World Application Patterns course
LaravelJune 26, 20263 min read

Scheduled Tasks and Cron Jobs: Automating Laravel Workflows

Learn to master Laravel scheduling to automate recurring tasks like reporting and cleanup. Replace complex crontabs with clean, version-controlled PHP code.

LaravelSchedulingAutomationCronDevOpsArtisanphpbackend

Previously in this course, we explored Command Line Tools with Artisan: Automating Laravel Workflows. Now that you can build custom CLI commands, the next logical step is automating their execution. Instead of managing dozens of individual server-level cron jobs, Laravel allows you to define your entire schedule within your application code.

The Problem with Traditional Cron

In a standard Linux environment, you would edit your crontab file to run commands. This approach is brittle: your schedule lives outside your repository, it's hard to version control, and it's a nightmare to manage across staging and production environments.

Laravel’s scheduling system acts as a wrapper around the system cron. You only need to add a single entry to your server's crontab, and Laravel handles the rest.

Defining Scheduled Tasks

In modern Laravel versions, the schedule is defined in routes/console.php. You use the Schedule facade to define tasks that should run at specific intervals.

Let’s advance our project board application. We want to automatically delete tasks that have been marked as "archived" for more than 30 days.

First, ensure you have an Artisan command (as learned in our previous lesson) called app:prune-old-tasks. Now, register it in routes/console.php:

PHP
use Illuminate\Support\Facades\Schedule;

Schedule::command('app:prune-old-tasks')->daily();

The daily() method is a helper for a standard cron expression. You can also use everyMinute(), weekly(), or monthly().

Advanced Scheduling with Cron Expressions

When built-in helpers aren't enough, you can use the cron() method to pass raw cron expressions. This gives you full control over the timing.

For example, if you need to run a report every Monday at 3:00 AM:

PHP
Schedule::command('app:generate-weekly-report')
    ->cron('0 3 * * 1');

You can also chain methods to control execution constraints:

PHP
Schedule::command('app:prune-old-tasks')
    ->dailyAt('02:00')
    ->environments(['production'])
    ->withoutOverlapping();
  • environments(['production']): Prevents the task from running in local or staging environments.
  • withoutOverlapping(): Ensures that if the previous execution is still running, the new one won't start. This is critical for long-running cleanup jobs.

Handling Task Output

When tasks run in the background, you won't see their output in your terminal. To debug or keep a record, you should direct the output to a log file or send it via email.

PHP
Schedule::command('app:prune-old-tasks')
    ->daily()
    ->appendOutputTo(storage_path('logs/scheduler.log'))
    ->emailOutputOnFailure('admin@example.com');

Using appendOutputTo is essential for production monitoring. If a task fails silently, you need that log file to diagnose the issue.

Hands-on Exercise

  1. Open your project's routes/console.php file.
  2. Register a new task that runs app:generate-weekly-report every Sunday at midnight.
  3. Add withoutOverlapping() to ensure it doesn't collide with other processes.
  4. Append the output to storage/logs/reports.log.
  5. Verify your schedule by running php artisan schedule:list in your terminal.

Common Pitfalls

  • Forgetting the single Cron entry: You must add * * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1 to your server’s crontab. Without this, your defined schedule will never trigger.
  • Overlapping Tasks: If a task takes longer than the interval (e.g., a report that takes 2 minutes to generate but is scheduled everyMinute), you will end up with multiple processes competing for database locks. Always use withoutOverlapping().
  • Environment Leaks: Running cleanup commands in your local environment can be destructive. Always use ->environments(['production']) for sensitive tasks.

Recap

Scheduling in Laravel turns complex server management into readable, version-controlled code. By using the Schedule facade, we can define our task intervals, handle overlaps, and ensure our application maintains its health through automated cleanup and reporting. This is a core component of building robust, autonomous systems.

Up next: We will dive into Job Chaining and Batching, where we'll learn how to handle complex, multi-step background processes that depend on each other.

Previous lessonCommand Line Tools with ArtisanNext lesson Integrating Third-Party Services
Back to Blog

Similar Posts

LaravelJune 26, 20263 min read

Command Line Tools with Artisan: Automating Laravel Workflows

Learn how to build custom Artisan commands to automate development tasks. Master CLI arguments, options, and console interaction to streamline your Laravel app.

Read more
LaravelJune 28, 20264 min read

Advanced Database Migration Strategies for Laravel

Master non-breaking migrations and safe rollback procedures. Learn the expand-and-contract pattern to evolve your database schema without production downtime.

Part of the course

Intermediate Laravel: Real-World Application Patterns

intermediate · Lesson 33 of 58

  1. 1

    Architecting for Maintainability

    3 min
  2. 2

    Implementing the Service Layer

    3 min
  3. 3

    Repository Pattern Fundamentals

    3 min
Read more
LaravelJune 28, 20264 min read

Optimizing Asset Pipelines: Versioning and CDN Caching with Vite

Master production-grade asset management in Laravel. Learn to implement file hashing for versioning and configure Vite to scale your frontend performance via CDN.

Read more
  • 4

    Project Board Domain Modeling

    3 min
  • 5

    Advanced Eloquent Scopes and Accessors

    4 min
  • 6

    Service-Oriented Task Management

    3 min
  • 7

    REST API Fundamentals with Sanctum

    3 min
  • 8

    Resource Controllers and API Responses

    3 min
  • 9

    Handling API Validation and Form Requests

    3 min
  • 10

    Implementing Middleware for API Security

    4 min
  • 11

    Database Transactions for Data Integrity

    3 min
  • 12

    Error Handling and Global Exceptions

    3 min
  • 13

    Introduction to Laravel Events and Listeners

    3 min
  • 14

    Asynchronous Processing with Queues

    4 min
  • 15

    Job Chaining and Batching

    3 min
  • 16

    Feature Testing Fundamentals

    4 min
  • 17

    Mocking Services and Repositories in Tests

    3 min
  • 18

    Testing Events and Jobs

    3 min
  • 19

    Database Factories and Seeding

    3 min
  • 20

    API Versioning Strategies

    4 min
  • 21

    Advanced Request Filtering and Sorting

    3 min
  • 22

    Handling File Uploads in REST APIs

    3 min
  • 23

    Real-time Notifications with Broadcasting

    3 min
  • 24

    Using Observers for Model Lifecycle Hooks

    3 min
  • 25

    Implementing Policies for Authorization

    3 min
  • 26

    Customizing Authentication Guards

    3 min
  • 27

    Rate Limiting API Endpoints

    4 min
  • 28

    Eloquent Performance Optimization

    4 min
  • 29

    Caching Strategies for Performance

    4 min
  • 30

    Using Traits for Code Reuse

    3 min
  • 31

    Advanced Dependency Injection with Service Providers

    3 min
  • 32

    Command Line Tools with Artisan

    3 min
  • 33

    Scheduled Tasks and Cron Jobs

    3 min
  • 34

    Integrating Third-Party Services

    3 min
  • 35

    Handling Webhooks

    3 min
  • 36

    Logging and Monitoring

    3 min
  • 37

    Database Migrations Best Practices

    3 min
  • 38

    Advanced Testing: Integration Tests

    4 min
  • 39

    Testing API Authentication

    4 min
  • 40

    Code Quality and Static Analysis

    3 min
  • 41

    Project Structure for Large Applications

    3 min
  • 42

    Environment and Configuration Management

    3 min
  • 43

    Deploying Laravel Applications

    4 min
  • 44

    Database Indexing Strategies

    4 min
  • 45

    Using Value Objects

    4 min
  • 46

    Strategy Pattern for Business Rules

    3 min
  • 47

    Advanced Queue Monitoring

    3 min
  • 48

    Building a Search API

    3 min
  • 49

    Handling Concurrency and Race Conditions

    4 min
  • 50

    API Documentation with OpenAPI

    3 min
  • 51

    Testing with Test Doubles

    3 min
  • 52

    Implementing Multi-Tenancy

    4 min
  • 53

    Refactoring Legacy Code

    4 min
  • 54

    Using Middleware for Feature Flags

    3 min
  • 55

    Building Reusable Packages

    4 min
  • 56

    Performance Profiling

    3 min
  • 57

    Secure API Design

    3 min
  • 58

    Event Sourcing Concepts

    4 min
  • View full course