ClickCease

CYBER MONDAY SALE ✨ USE CODE: DEVRIMS60 ✨ 60% OFF FOR 5 MONTHS ✨ CLAIM NOW

laravel-cron-jobs

How to Use Laravel Cron Jobs?

Anmol Lohana

How to Use Laravel Cron Jobs?

laravel-cron-jobs

Table of Contents

Introduction

Laravel is one of the most commonly used PHP frameworks. There are situations for developers when they have to schedule tasks rather than manually edit or view code. For this reason, Laravel cron job is used. This article will help you learn about Laravel cron jobs, scheduling, and the most commonly used cron job commands.

What is Laravel Cron Job?

Cron’s job is a Unix command for job scheduling to be executed at a specific interval. For instance, you may send daily/weekly reports by task scheduling. It will execute a script to auto send the reports.

Cron jobs are used for data cleaning, email sending, executing time-consuming tasks, etc. Suppose you want to auto-delete records that are older than a month from the database every day at midnight. Cron Job will do that for you.

For scheduling, a configuration file known as Crontable or Crontab is used.  A crontab may comprise various cronjobs. Cronjob contains two parts, namely a shell command and a Cron expression. Every Cronjob has a particular task.

The format of the Cron scheduler is as follows:

* * * * * command/to /run

* Will be replaced by minute, hour, day, month, day of the weak.

Provided that:

  • Minute (0-59)
  • Hour (0-23)
  • Day of month (1-31)
  • Month (1-12)
  • Day of the week (0-6 starting on Sunday-0)

Cron job will be executed at regular intervals or defined times according to the details specified in the cron. 

Laravel Cron Job Samples

Every hour on the 10th minute of the hour.

10 * * * * command-to – run

If you want to run on every hour on the 10th minute of the hour on Tuesdays, then:

10 * * * 2 command-to- run

If you want to run a cron job at regular intervals of time, for example, every 20 minutes, then

*/20 * * * * command- to – run
Schedules

You can define schedule tasks in the schedule method of a kernel class of your application located at App/Console/Kernel.

Some examples are mentioned below to schedule tasks with different commands.

Task Scheduling in Laravel

The command scheduler feature in Laravel enables you to define the command schedule within Laravel. For scheduling, you should use SSH to add cron entries. You will need a single Cron entry on a server for running the Laravel task scheduler every minute.

laravel cron jobLaravel’s tasks schedule is defined inside the app/Console/Kernel.php file. Laravel’s task scheduler is defined in the schedule method.

Many tasks can be defined with the help of this method. The Cron entry you will need to add to your server for calling the Laravel command scheduler is as follows.

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

The above cronjob will start the task scheduler in order to run tasks inside the schedule method.

Command Scheduling in Laravel

We may use the Laravel task scheduler for scheduling the commands. Tasks were defined inside the schedule method of the Kernel class. Command method enables artisan commands. In contrast, the schedule method enables the schedule of all commands. You may set different frequencies that may apply to commands to need. A few of the examples are mentioned below:

If a task is supposed to execute once a day, then the daily() method is valid.

Protected function schedule(Schedule $schedule)
{
$schedule->command(‘sms:gudmorning’)->daily();
}
--    If we want to run tasks every hour every day.
$schedule->command(‘Task’)
->hourly();

For example, you want to run a task daily at 11.30 then    

$schedule->command(‘Task’)
->dailyAt(‘11.30’);

If you have to run a job every week, then:

$schedule->command(‘Task’)
->weekly( ); 

If you have to run a job every month, then:

$schedule->command(‘Task’)
->monthly( );

Apart from the above, we may also provide schedule constraints. We may combine the above methods to perform some actions if we need.   

$schedule->command(‘Task’)
->weekly( );
->mondays();
->at(10.30);
Scheduling Artisan Commands

Laravel Cron jobs may be implemented in various ways, and we’ve already seen how closures can be used to schedule these tasks.

The use of artisan commands to manage tasks in an application is the other technique. Laravel provides an interactive command-line interface for us to use to construct commands.

Let’s make a command that will be used to schedule tasks.

By running the following command, we will construct a command to schedule emails:

PHP artisan make: command emails

It will create the emails.php file in the app/Console/Commands directory.

What is PHP artisan Command?

You might not be familiar with Laravel artisan commands if you haven’t worked with them before. Developers use PHP Artisan to accomplish a variety of critical actions, such as producing migrations, publishing package assets, and other related tasks.

In Artisan, you may not only use built-in Laravel commands, but you can also create your unique Laravel commands.

You may use many pre-built Laravel artisan commands, but many developers prefer to construct their commands based on their project requirements. Type the following command to see a list of pre-built PHP Laravel artisan commands.

PHP artisan list

The whole list of built-in PHP Laravel artisan commands will be provided. These instructions aid developers in performing their tasks more efficiently, ultimately saving their time. You can construct auth, controller, model, mail, migration, and many other functions using these Laravel artisan commands.

Run Schedule Command for a test

To check if schedule commands have been constructed successfully, run this command.

php artisan schedule: run

After that, go to the logs folder inside the storage directory, open the Laravel.php cron job file, and check it.

Note: You can use this command when you want a Laravel scheduler without a cron job.

Scheduling Closure calls

You may also schedule a closure for calling every day at midnight, and within the closure, a database query will be executed for clearing the table.

protected function schedule(Schedule $schedule)
{
       $schedule->call(function () {
           DB::table('recent_users')->delete();
       })->daily();
}
Scheduling Exec/Shell Commands

If you want to issue a command to the operating system, then you should use the exec command

$schedule->exec('node /home/forge/script.js')->daily();
Schedule Queued Jobs

A queued job can be scheduled using the job method. This function makes it simple to schedule queued jobs without having to use the call method to declare closures:

$schedule->job(new JobName)->everyFiveMinutes();
Schedule options available in Laravel

We may use various schedules in our tasks. A few of them are as follows:

The different types of schedules we can assign to our tasks are,

->cron(‘* * * * * *’);           —        Use to run the task on a custom Cron schedule
->everyMinute();                 —        Use to run the task every minute
->everyFiveMinutes();            —        Use to run the task every five minutes
->everyTenMinutes();             —        Use to run the task every ten minutes
->everyThirtyMinutes();          —        Use to run the task every thirty minutes
->hourly();                      —        Use to run the task every hour
->daily();                       —        Use to run the task every day at midnight
->dailyAt(’13:00′);              —        Use to run the task every day at 13:00
->twiceDaily(1, 13);             —        Use to run the task daily at 1:00 & 13:00
->weekly();                      —        Use to run the task every week
->monthly();                     —        Use to run the task every month
->monthlyOn(4, ’15:00′);         —        Use to run the task every month on the 4th at 15:00
->quarterly();                   —        Use to run  the task every quarter
->yearly();                      —        Use to run  the task every year
->timezone(‘America/New_York’);  —     Use to run Set the timezone

Moreover, additional schedule constraints are listed as follows:

->weekdays();      —   Use to Limit the task to weekdays
->sundays();       —  Use to run Limit the task to Sunday
->mondays();       —   Use to run Limit the task to Monday
->tuesdays();      —   Use to run Limit the task to Tuesday
->wednesdays(); —   Use to run Limit the task to Wednesday
->thursdays(); —   Use to run Limit the task to Thursday
->fridays();       —  Use to run  Limit the task to Friday
->saturdays(); —   Use to run Limit the task to Saturday
->when(Closure); —  Use to run Limit the task based on a truth test

Note:

Laravel Task Scheduler has many advantages; one of the most important advantages is that we can focus on creating commands and writing logic. It is manageable by other co-workers because it is now tracked by version control. Laravel will take care of the rest.

If you want to deploy your application on the server in just one click, get the Laravel hosting.

Conclusion

In this article, I discussed practical ways to schedule tasks using different Laravel commands. The most commonly used schedules and ways to assign tasks to the scheduler according to time were demonstrated. Share your experience with Laravel cron job in the comments section.

Share it!

Share it!

Start Creating Web Apps on Managed Devrims Cloud Server Now

Easy Web Deployment for Agencies, Developers and e-commerce Industry.

There's More To Read

Laravel SEO Guide

Search engine optimization (SEO) has become crucial for businesses looking to increase their online visibility and attract more traffic from search engines. In today’s digital world, consumers rely heavily on

Read More »

10 Best PHP Editors and IDEs

In this article, we’ll cover the 10 best PHP editors and integrated development environments (IDEs) for advancing your coding experience and productivity. We understand the importance of having the right

Read More »