cron job in laravel 4.2

Below I detail a tutorial for using commands in Laravel 4 with cron. I have divided into four steps to make it easier to follow.

STEP #1: Create a command in Laravel 4:

php artisan command:make RefreshStats
With command above, Laravel will create a file named RefreshStats.php in directory app/commands/

RefreshStats.php it's a file like this:
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class RefreshStats extends Command {

        protected $name = 'command:name';
        protected $description = 'Command description.';

        public function __construct() {
                parent::__construct();
        }

        public function fire(){

        }

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

        protected function getOptions() {
            return array(
                array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null),
            );
        }

}


STEP #2: Simple "configuration" of RefreshStats file:

You should change this line:
protected $name = 'command:name';
to something like this:
protected $name = 'refresh:stats';
If you don't need arguments (same for options), 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 RefreshStats);


STEP #4: Create CRON scheduled task:

Finally, you can add a scheduled task as follow:
crontab -e
And add a line (run command every 30 minutes) like below:
*/30 * * * * php path_laravel_project/artisan refresh:stats

No comments:

The 6 New Rules of Communicating

The era of teleprompters and talking points has come to an end ͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­͏     ­...

Contact Form

Name

Email *

Message *