Implementing cron jobs with Yii

You are viewing revision #1 of this wiki article.
This is the latest version of this article.

  1. Emulating browser
  2. Using console application

There are two ways to run a cron job:

  • Emulate browser.
  • Run PHP in CLI (console) mode.

Emulating browser

This way is a simplest one since you can use existing controller action.

Add one of the following to your crontab: ~~~ GET http://example.com/cron/ ~~~

wget -O - http://example.com/cron/
lynx --dump http://example.com/cron/ >/dev/null

In spite of this method is simple, there are drawbacks. If we are doing some kind of intensive job, one who know the URL can kill your application sending a lot of requests to it.

You can pass a parameter and check it in your action to make URL harder to find:

if($_GET['key']!='my_secret_key') die();

but this will not solve the problem completely.

Using console application

The best way is to create a console application.

Let's create a console command class /protected/commands/TestCommand.php:

class TestCommand extends CConsoleCommand {
    public function run($args) {
        // here we are doing what we need to do
    }
}

Creating entry script cron.php:

defined('YII_DEBUG') or define('YII_DEBUG',true);

// including Yii
require_once('path/to/yii/framework/yii.php');

// we'll use a separate config file
$configFile='path/to/config/cron.php';

// creating and running console application
Yii::createConsoleApplication($configFile)->run();

Configuration file should look like this:

return array(
    // This path may be different. You can probably get it from `config/main.php`.
    'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
    'name'=>'Cron',

    'preload'=>array('log'),
    
    'import'=>array(
		'application.components.*',
		'application.models.*',
    ),
    // We'll log cron messages to the separate files
    'components'=>array(
		'log'=>array(
			'class'=>'CLogRouter',
			'routes'=>array(
				array(
					'class'=>'CFileLogRoute',
                    'logFile'=>'cron.log',
					'levels'=>'error, warning',
				),
				array(
					'class'=>'CFileLogRoute',
					'logFile'=>'cron_trace.log',
					'levels'=>'trace',
				),
			),
		),

        // Your DB connection
		'db'=>array(
			'class'=>'CDbConnection',
			// …
		),
    ),
);

In your crontab add: ~~~ php /path/to/cron.php test ~~~ Where test is a command name.

27 2
27 followers
Viewed: 114 006 times
Version: Unknown (update)
Category: How-tos
Tags: cli, cron
Written by: samdark
Last updated by: samdark
Created on: Oct 26, 2010
Last updated: 13 years ago
Update Article

Revisions

View all history

Related Articles