X
    Categories: Laravel

Cron job in Laravel

Cron job in Laravel

In this tutorial we are going to see how to create cron job using Laravel. Cron job does not read the controller file, So we need to add cron job using commands.
Just 4 Steps to create Cron Job in Laravel.

STEP 1 :

Create Command in Laravel By using Below command.
Run the command in composer.

php artisan command:make CronCommand

It will create the command File which is named as CronCommand inside the folder app/commands/CronCommand.php

CronCommand.php File code will like below.

<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class CronCommand extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $name = 'command:name';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Command description.';

	/**
	 * Create a new command instance.
	 *
	 * @return void
	 */
	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function fire()
	{
		 echo "Hello world";
	}

	/**
	 * Get the console command arguments.
	 *
	 * @return array
	 */
	protected function getArguments() {
      return array(
          array('example', InputArgument::REQUIRED, 'An example argument.'),
      );
	}

	/**
	 * Get the console command options.
	 *
	 * @return array
	 */
	protected function getOptions()
	{
		return array(
			array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null),
		);
	}

}

STEP 2 : Simple “configuration” of CronCommand file:

You should change this line:


protected $name = 'command:name';

to something like this:

protected $name = 'run:cronjob';

If you don’t need arguments, change this line:

protected function getArguments() {
      return array(
          array('example', InputArgument::REQUIRED, 'An example argument.'),
      );
}

to:

protected function getArguments() {
      return array();
}

And now pay attention to the fire function. The command will execute source code that is wrote in that function. Example:

public function fire(){
    echo "Hello world";    
}

 STEP #3: Register the command:

You need to register the command. So open app/start/artisan.php file, and add one line as below:

Artisan::add(new CronCommand);

 STEP #4: Create CRON scheduled task:

*/30 * * * * php path_laravel_project/artisan run:cronjob

Thats it, Now your command function will execute every 30 minutes.

If you like this article, Please don’t forget to share and comment.

Thanks!.

Marimuthu: