Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Cron Job in Laravel 4

Tags:

php

cron

laravel

I need a Cron job for execute a Scraper to a Website and send emails with the information, I made a Controller to do that, but when I set up the command to run that file

php app/controllers/ScraperController.php 

I get this error

PHP Fatal error: Class 'BaseController' not found in /var/www/U-Scraper/app/controllers/ScraperController.php on line 2

The thing is, it works when I set up with a route to that controller

like image 514
Bryan Villafañe Avatar asked Oct 03 '13 03:10

Bryan Villafañe


2 Answers

Controllers don't run by themselves, they work as a component of Laravel. If you're loading your controller directly then Laravel is not being loaded and as far as PHP is concerned BaseController, as well as Laravel's Controller class, does not exist. Normally your web server loads public/index.php which loads Laravel and so on. If that's confusing you may want to learn about how autoloading with Composer works: http://net.tutsplus.com/tutorials/php/easy-package-management-with-composer/

What you should do is write an Artisan command that does what you need and call that command using cron. This question gives details on how to accomplish this: Cron Job in Laravel

like image 58
Brian Ortiz Avatar answered Oct 18 '22 22:10

Brian Ortiz


I suggest you to create new Artisan command instead of controller.

Then set CRON task to run your command, for example:

1 * * * * /usr/bin/php /path/to/the/artisan nameofthecustomcommand

If you cannot run/set task this way, but you can set the URL to execute

http://mydomain.com/cron.php

// cron.php
// I am aware I do use exec()
exec('php artisan nameofthecustomcommand');

More about Artisan commands here

There is a chance, you can put whole controller method into this command without having to touch the code ;)

like image 3
Andreyco Avatar answered Oct 18 '22 21:10

Andreyco