Home » Php » Running Laravel Task at specific time

Running Laravel Task at specific time

Posted by: admin November 29, 2017 Leave a comment

Questions:

I’ve seen some similar questions at SO but none of then have answered me. I had never heard of CRON before and I’m new to Laravel. What I need is to run a Task once a week to perform some actions on my database (MySql), say every sunday at 12:00 am. How could I achieve this goal?

Answers:

If you can use cron, you just have to execute

crontab -e

Or, if you need to run as root:

sudo crontab -e

This will open a text editor so you can modify your crontab and there you’ll have one line for each scheduled command, as this one:

1 0 * * *  php /var/www/myBlog/artisan task:run

The command in this like will be executed at the first minute of every day (0h01 or 12h01am).

Here is the explanation of it all:

*    *    *    *    *  <command to execute>
┬    ┬    ┬    ┬    ┬
│    │    │    │    │
│    │    │    │    │
│    │    │    │    └───── day of week (0 - 6) (0 to 6 are Sunday to Saturday, or use names)
│    │    │    └────────── month (1 - 12)
│    │    └─────────────── day of month (1 - 31)
│    └──────────────────── hour (0 - 23)
└───────────────────────── min (0 - 59)

So, in your case, you’ll create a line like this:

0    12    *    *    0  <command to execute>

But how do you do that for a task in Laravel? There are many ways, one of them is in my first example: create an artisan command (task:run) and then just run artisan, or you can just create a route in your app to that will call your task every time it is hit:

Route::get('/task/run',array('uses'=>'[email protected]'));

And then you just have to add it your crontab, but you’ll need something to hit your url, like wget or curl:

0  12  *  *  0  curl http://mysite.com/run/task

Questions:
Answers:

Since Laravel 5, the only entry you need to put into crontab after executing crontab -e is

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

Do remember to change /path/to/artisan part to your project specific path.

And then you can define your scheduled tasks and running frequency in Laravel’s App\Console\Kernel class. See Laravel documentation for more information: Task Schedule

Questions:
Answers:

You can create and run your laravel tasks from the command line just like any other Artisan command. So if you are on windows you can just run the command manually to see if it works or not.

Then when you are on production server (better of course if it is Unix based) then you can follow Antonio’s direction to create the cron job and add it to the cron tab. Keep in mind you will need to know the complete paths for the PHP execution.

My tutorial explains this all in detail : http://maxoffsky.com/code-blog/practical-laravel-using-cron-jobs-in-laravel/

Hope you find the answer that you are looking for.