
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.
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
In this article you will learn
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
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.
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.
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: changepath-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
.
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();
}
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.
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();
}
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.
You can save the output to certain file for inspecting later.
$schedule->command('emails:send')
->daily()
->sendOutputTo($filePath);
If you want to append to specific file.
$schedule->command('emails:send')
->daily()
->appendOutputTo($filePath);
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');
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...
});
Here I have illustrated simple usage of cronjob with Laravel. Please use this documentation for full fledged features Laravel Task Scheduling.
Create / Save / Download PDF From Blade Template In PHP Laravel
Free SSL Certificate With Lets Encrypt/Certbot In Linux (Single / Multiple Domains)
Laravel 7.x Multiple Database Connections, Migrations, Relationships & Querying
What Is Laravel Resourceful Controllers?
Create Zip File On The Fly With Streaming Download In PHP Laravel
Multiple File Uploads In Laravel PHP
Proper Way To Validate MIME Type Of Files While Handling File Uploads In PHP
Send SMS With Amazon SNS (Simple Notification Service) Using PHP
Accessors And Mutators In PHP Laravel
Simple Way To Create Resourceful API Controller In Laravel
Generate Sitemap in PHP Laravel
Send Email In PHP With PHPMailer