Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







Why You Should Run Cronjobs In Laravel?


Share On     Share On WhatsApp     Share On LinkedIn


Hello! this article is the sequel of How To Automate Repeating Tasks In Linux Server With Cronjobs article.


To summarise in previous article I had explained

  1. What Is Cronjob
  2. Cronjob Syntax
  3. How & Where To Add Cronjobs
  4. Examples To Make The Cronjob Understand Easier
  5. Automate Database Backup With Cronjob
  6. Automate Sitemap Generation
  7. Automate RSS Generation


In this article you will learn

  1. Why Use Laravel Task Scheduling
  2. How To Add Laravel Task Scheduling In Crontab
  3. Running Task Scheduling In Laravel
  4. Adding Custom Functions & Console Commands For Task Scheduling
  5. Task Scheduling Frequency
  6. Other Useful Strategies

Prerequisites


You need to know basics of cronjob. But not necessary. You can refer this article if your interested to learn more on the cronjob How To Automate Repeating Tasks In Linux Server With Cronjobs


Why Use Laravel Task Scheduling


Problem


There is nothing wrong in using old school Cronjob and writing commands for that.


But the problem is every time you make any changes to script timings or add new script to cron scheduling then you have to literally login to server and make the changes. And even there wont be any version control to handle everything at one place for these tasks.


Solution


Laravel has a feature called as Task Scheduling. It can be easily tracked with version control & no need to login to server for every new tasks you create.


How To Add Laravel Task Scheduling In Crontab


To make all your cronjob run same as the earlier it used to run, just add the following command in crontab


First edit the crontab with the following command


sudo crontab -e


Then add the following command


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


The above command will run Laravel schedule:run command every minute and check if there are any task need to be run.


NOTE: change path-to-your-project with your project location, most of the times it will be in /var/www/html/project_name or /var/www/project_name.

Running Task Scheduling In Laravel


To run any tasks in Laravel you just need to register you console commands or closure functions to run at specific time in app/Console/Kernel.php as below:


$schedule->command() - To run Laravel command line scripts

$schedule->call() - To run Laravel function as a closure. Inside closure you can call any other controller methods


Inside app/Console/Kernel.php -> Schedule function


protected function schedule(Schedule $schedule)
{
    /** Run Laravel Commands With $schedule->command */
    $schedule->command('sitemap:generate')->daily();
    $schedule->command('rss:generate')->daily();


    /** Run Controller Functions With $schedule->call Closure */
    $schedule->call(function(){
        /** Here I am calling database cleaning command from CleanUpDatabase Controller */
        (new CleanUpDatabase())->clean();
    })->daily();
}

Adding Custom Functions & Console Commands For Task Scheduling


Custom Controller Functions


You can call your custom Controller functions with $schedule->call() as follows

protected function schedule(Schedule $schedule)
{
    /** Run Controller Functions With $schedule->call Closure */
    $schedule->call(function(){
        /** Here I am calling database cleaning command from CleanUpDatabase Controller */
        (new CleanUpDatabase())->clean();
    })->daily();
}


You can even write the entire code inside the above closure function() but I don't recommend as it will clutter up you schedule function and eventually start bloating. Let me show you an example


I don't recommend you guys to write the code as below


protected function schedule(Schedule $schedule)
{
    /** Run Controller Functions With $schedule->call Closure */
    $schedule->call(function(){
        /** Send articles list via mail weekly for subscribers  */
        $users = App\Models\User::subscribers()->get();
        foreach($users as $user){
            /** Send mail to suers */
        }
    })->weekly();
}


As you can see from the above example just one custom function occupied so much of code and your Scheduler started bloating.


Console Commands


You can call the console commands from the Task Scheduler easily with $schedule->command()


protected function schedule(Schedule $schedule)
{
    /** Run Laravel Commands With $schedule->command */
    $schedule->command('sitemap:generate')->daily();
    $schedule->command('rss:generate')->daily();
}

Task Scheduling Frequency


In the above examples you saw that the scheduling frequency is daily() or weekly(). Other than these there are lot of other too let me show few on them.


->cron("* * * * *") - Run your custom cronjob timings, here its running every minutes

->daily() - Run cronjob daily mid night

->dailyAt('14:00') - If you wan to run daily at specific time, here it run at 2PM in afternoon

->weekly() - Run cronjob weekly at midnight

->everyMinute() - Run cronjob every minute

->hourly() - Every one hour


For detailed list of all functions you can use this link Laravel Scheduling Frequency.


Other Useful Strategies


Sending Output To File


You can save the output to certain file for inspecting later.


$schedule->command('emails:send')
    ->daily()
    ->sendOutputTo($filePath);



Append The Output To Existing File


If you want to append to specific file.


$schedule->command('emails:send')
    ->daily()
    ->appendOutputTo($filePath);



Email Output


You can also send email of output, but you should have your email configured with Larvel.


$schedule->command('foo')
         ->daily()
         ->sendOutputTo($filePath)
         ->emailOutputTo('foo@example.com');

Task Scheduling Hooks


You can use the hooks with task scheduling to keep track of few things or to logs


i. before() & after()


If you want something to get executed before and after the task then you can


$schedule->command('emails:send')
    ->daily()
    ->before(function () {
      // Task is about to start...
    })
    ->after(function () {
      // Task is complete...
    });



ii. On success() or failure()


$schedule->command('emails:send')
    ->daily()
    ->onSuccess(function () {
      // The task succeeded...
    })
    ->onFailure(function () {
      // The task failed...
    });


Conclusion


Here I have illustrated simple usage of cronjob with Laravel. Please use this documentation for full fledged features Laravel Task Scheduling.







Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing