Sunday, 24 July 2016

Task Scheduling in Laravel

Scheduling Task In Laravel



In the past, developers have generated a Cron entry in the cron file 

for each task they need to schedule. However, this is a headache 

and time consuming task. Your task schedule is no longer in source 

control, and you must SSH into your server to add the Cron entries 

in the cron file. The Laravel command scheduler allows you to 

fluently and expressively define your command schedule within 

Laravel itself, and only a single Cron entry is needed on your 

server, it makes you very easy to control on you commands.


I will show the entire process of scheduling the task by an example,


which will insert logs every minute in log file. Please follow the 


steps and you are done with Task Scheduling



Step 1:


Inside you project folder type this below command




php artisan make:console LogDemo –command=log:demo



Step2:



go to /app/console/commands/


you will see a file names as logDemo.php that is your newly 


created file Open it and add the below line which will put log in the log file.



Log::info('Showing user profile for user');


Next task is to register this command so that kernel can actually 


know it.


Step3:


Open kernel.php file and add this line


Commands\LogDemo::class,


inside protected $commands = [ ];


After adding it will look like this



protected $commands = [


//Commands\Inspire::class,


 Commands\LogDemo::class,
];




Step 4:


4.1


  crontab -e


4.2 Add the below line in your cron tab


* * * * * php /var/www/html/laravelTarun/artisan schedule:run 1>> 

/dev/null 2>&1


Here /var/www/html/laravelTarun/ is your path to the  project


4.3 Now Add the below line to your Kernel.php file


$schedule->command('log:demo')->everyMinute();


This will run the log:demo command every minute and store the 

output in the log file.


That's it open laravel.log file inside /storage/logs/ directory 

wait for 1 minute and you will see the log


my file output after 7 minute:



[2016-07-24 09:08:57] local.INFO: Showing user profile for user

[2016-07-24 09:09:11] local.INFO: Showing user profile for user

[2016-07-24 09:18:02] local.INFO: Showing user profile for user

[2016-07-24 09:19:01] local.INFO: Showing user profile for user

[2016-07-24 09:20:01] local.INFO: Showing user profile for user

[2016-07-24 09:21:01] local.INFO: Showing user profile for user

[2016-07-24 09:22:01] local.INFO: Showing user profile for user


That's it your have learned how the schedule task in laravel.


No comments:

Post a Comment