DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Mastering Concurrency: An In-Depth Guide to Java's ExecutorService
  • A Step-By-Step Guide: How To Install a Laravel Script
  • How To Use the Node Docker Official Image
  • Maximizing Laravel's Potential: A Guide to Driver-Based Services

Trending

  • Building Scalable and Resilient Data Pipelines With Apache Airflow
  • Rethinking Recruitment: A Journey Through Hiring Practices
  • Segmentation Violation and How Rust Helps Overcome It
  • Doris: Unifying SQL Dialects for a Seamless Data Query Ecosystem
  1. DZone
  2. Coding
  3. Frameworks
  4. Laravel Cron Scheduling and Its Secrets

Laravel Cron Scheduling and Its Secrets

If the number of cron tasks increase, or their effort becomes too heavy, there are internal behaviors you need to know to avoid big headaches.

By 
Valerio Barbera user avatar
Valerio Barbera
·
May. 01, 22 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
5.7K Views

Join the DZone community and get the full member experience.

Join For Free

Hi, I’m Valerio Barbera, software engineer, founder, and CTO at Inspector.

One of the most useful features of Laravel is the tasks scheduling system. The official documentation clearly explains what it is for:

In the past, you may have written a cron configuration entry for each task you needed to schedule on your server. However, this can quickly become a pain because your task schedule is no longer in source control and you must SSH into your server to view your existing cron entries or add additional entries.

Laravel’s command scheduler offers a fresh approach to managing scheduled tasks on your server. The scheduler allows you to fluently and expressively define your command schedule within your Laravel application itself. When using the scheduler, only a single cron entry is needed on your server.

Some common use cases for scheduled tasks:

  • Daily/weekly/monthly summary reports
  • Garbage collection
  • Import/export processes
  • Notifying customers of upcoming expirations (account, credit cards, and so on)

I myself have worked a lot with this component of the framework because there are some parts of the Inspector backend system that depend on it. 

Experimenting with the first tasks can give you a lot of happiness, but when the number of tasks increase, or their internal effort becomes too heavy, there are some non-intuitive behaviors you need to know to avoid big headaches later and to be ready for a sustainable application growth.

How Laravel Scheduling Works

Laravel tasks scheduling is designed like a proxy for your cron scheduling list. You only need one line on the cron file in your server:

 
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

It instructs the cron scheduler to run this artisan command every minute. 

Without going too deep, analyzing the implementation of the \Illuminate\Console\Scheduling\ScheduleRunCommand class, you can see that it iterates events defined in the App\Console\Kernel class that are ready to be executed in a foreach cycle, and runs them with runEvent method.

PHP
 
foreach ($this->schedule->dueEvents($this->laravel) as $event) {
	
	//...
	
	$this->runEvent($event);
	
	//...
}

It is in charge of executing all the commands defined in the App\Console\Kernel class based on the frequency you have configured for each of them.

How to Schedule a Task

Imagine you need to check your blog posts every 10 minutes to send an alert if they are unreachable. You can schedule this command:

PHP
 
namespace App\Console;

use App\Console\Commands\PostsCehckCommand;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
		
        $schedule->command(PostsCheckCommand::class)->everyTenMinutes();
		
    }
	
}

The Laravel scheduler provides fluent and expressive APIs to help you define the way a command must be run.

Every time you need to run a task, you can add a new line in the scheduler to define what task should be executed and its frequency.

Parallel Execution

Checking out the code of the ScheduleRunCommand class by default, multiple tasks scheduled at the same time will execute sequentially based on the order they are defined in your schedule method. 

The command uses a foreach cycle to iterate events ready to be executed, so if you have long-running tasks, or the list of tasks is lengthy, this may cause subsequent tasks to start much later than anticipated.

To simulate this scenario I created two commands:

  • SleepCommand (that contains five seconds' sleep)
  • AnotherCommand (that simply writes a new log line)

Then add the appropriate line to the scheduler:

PHP
 
/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
	$schedule->command(SleepCommand::class)->everyMinute();
	$schedule->command(AnotherCommand::class)->everyMinute();
}

Type the command below in your terminal to run the test: 

 
php artisan schedule:run

Logs will report the two lines with a five-second interval: 

If you prefer to run tasks in the background so that they may all run simultaneously, you may use the runInBackground method to prevent tasks from stepping on each other’s toes: 

PHP
 
/**
 * Define the application's command schedule.
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
	$schedule->command(SleepCommand::class)->everyMinute()->runInBackground();
	$schedule->command(AnotherCommand::class)->everyMinute();
}

Logs confirm that the sleep hasn’t any effect on the time the second command runs. 

I personally use the runInBackground option in every task by default.

Don’t Worry About Exceptions

Since the commands are executed in sequential order via the foreach loop, you may worry that an exception in one command will stop the entire cycle.

Fortunately, this is not so.

The ScheduleRunCommand simply reports exceptions via the Laravel exception handler without breaking the cycle so the next commands in the list can be executed as expected.

PHP
 
/**
 * Run the given event.
 *
 * @param  \Illuminate\Console\Scheduling\Event  $event
 * @return void
 */
protected function runEvent($event)
{
    $this->dispatcher->dispatch(new ScheduledTaskStarting($event));
	
	try {
		$event->run($this->laravel);

		$this->dispatcher->dispatch(new ScheduledTaskFinished($event);

	} catch (Throwable $e) {
		$this->dispatcher->dispatch(new ScheduledTaskFailed($event, $e));

		$this->handler->report($e);
	}
}

Visibility

Scheduled tasks are like a hidden part of your application, because they run away from users’ eyes. They are not tied to the user interaction like the code you write in the controllers.

Their presence pushes you to continuously check the logs (even on Saturday and Sunday) to be sure that no errors appear.

If something goes wrong during an HTTP request, it will causes red bubbles or messages that inform the user immediately of the problem. It’s quite easy to discover relevant errors before releasing the software in production using the application yourself.

If a scheduled command fails, however, it will do it silently, without anyone noticing.

Inspector is designed to remove these concerns from your daily effort. It works with a lightweight software library that you can install in your application like any other dependencies based on the technology you are using to develop your back end. Check out the supported technology on our GitHub (https://github.com/inspector-apm).

Laravel application Command (computing) Scheduling (computing) Task (computing)

Published at DZone with permission of Valerio Barbera. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Concurrency: An In-Depth Guide to Java's ExecutorService
  • A Step-By-Step Guide: How To Install a Laravel Script
  • How To Use the Node Docker Official Image
  • Maximizing Laravel's Potential: A Guide to Driver-Based Services

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!