How to use Cron Jobs with Laravel?

Anmol Lohana

How to use Cron Jobs with Laravel?

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 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 from our website to auto send the reports.

Cron jobs are used for data cleaning, email sending, executing time-consuming tasks, etc. Suppose you want to delete files from the database, such as files older than a month. Cronjob 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)

Cronjob will be performed for each minute or day or week or month or day of the weak according to the details specified above.

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 job - DevrimsLaravel’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 on facebook
Share on linkedin
Share on twitter

Share it!

Share on facebook
Share on linkedin
Share on twitter

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

For 3 Months Avail Free
Laravel Migration

Code: DEV30LAR

* T&C Apply

For 3 Months Avail Free
Laravel Migration

Code: DEV30LAR

No Thanks

* T&C Apply