Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Laravel Task at specific time

Tags:

cron

laravel

task

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?

like image 275
ecampver Avatar asked Jun 15 '13 23:06

ecampver


People also ask

What is cron job in Laravel 8?

Laravel 8 cronjob is task scheduling work according to the scheduled time. For example, If you want to schedule any task that will be executed every day, hours, minutes automatically. So in that case you can use laravel 8 cron job that is very helpful and also reduced manually working time.


2 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'=>'TaskController@run'));

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
like image 140
Antonio Carlos Ribeiro Avatar answered Oct 16 '22 00:10

Antonio Carlos Ribeiro


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

like image 21
Woodrow Norris Avatar answered Oct 16 '22 00:10

Woodrow Norris