How to Use Laravel Cron Jobs?

10 Min | June 10, 2024

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, a cron job in Laravel 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 in Laravel?

Cron’s job is a Unix command to execute job scheduling 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 older than a month from the database every day at midnight. Cron Job will do that for you.

A configuration file known as Crontable or Crontab is used for scheduling. A crontab may comprise various cronjobs. A cronjob contains two parts: 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)

The 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 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 your application’s kernel class, which is located at App/Console/Kernel.

Some examples are mentioned below for scheduling 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 to run the Laravel task scheduler every minute.

laravel cron job

Laravel’s task schedule is defined in the app/Console/Kernel.php file, and its task scheduler is defined in the schedule method.

This method helps define many tasks. To call the Laravel command scheduler, you must add the Cron entry to your server.

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

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

Command Scheduling in Laravel

We may use the Laravel task scheduler to schedule the commands. Tasks were defined inside the schedule method of the Kernel class. The 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 be executed 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( );

We may also provide schedule constraints. If necessary, we may combine the above methods to perform some actions.

$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.

Using artisan commands to manage tasks in an application is another 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 own unique Laravel commands.

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

PHP artisan list

A 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 the 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 for 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 Laravel hosting.

Conclusion

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

The Author

Anmol is a dedicated technical content writer known for her practical approach. She believes in experiencing processes firsthand before translating them into insightful content. Additionally, she is good at WordPress development and skills of digital forensics and cybersecurity. Beyond her professional endeavors, she enjoys playing sports games, particularly table tennis and badminton, valuing the balance between mental and physical agility.

Scroll to Top