Implementing cron jobs with Yii

  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 ~~~

wget -O -
lynx --dump >/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

// we'll use a separate config file

// creating and running console application

Configuration file should look like this:

return array(
    // This path may be different. You can probably get it from `config/main.php`.

    // We'll log cron messages to the separate files
					'levels'=>'error, warning',

        // Your DB connection
			// …

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

27 2
Viewed: 114 174 times
Version: 1.1
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


View all history

Related Articles