Cron Jobs in Yii

10 followers

This wiki article has not been tagged with a corresponding Yii version yet.
Help us improve the wiki by updating the version information.

I've gotten Yii running cron jobs, and wanted to explain briefly how I did it.

The first thing I did was set up a table for the job, using this migration:

$this->createTable('tbl_cron_jobs', array(
    'id' => 'pk',
    'execute_after' => 'timestamp',
    'executed_at' => 'timestamp NULL',
    'succeeded' => 'boolean',
    'action' => 'string NOT NULL',
    'parameters' => 'text',
    'execution_result' => 'text'
));

Next, I generated a model using Gii. Then I added two methods:

public function beforeValidate(){
        if(gettype($this->parameters) !== "string"){
            $this->parameters = serialize($this->parameters);
        }
        return parent::beforeValidate();
    }
 
    public function afterFind(){
        $this->parameters = unserialize($this->parameters);
        return parent::afterFind();
    }

When you are creating a new CronJob, pass any parameters in as an array and the Model will serialize them for you.

Next, we need the CronCommand so that we can process these jobs from the command line. I set mine up with one action (actionIndex) that processes all the jobs. It selects all the jobs that need to be executed that haven't yet been, and starts to process them.

For all the code, check out the github page at https://github.com/aarondfrancis/yii-CronCommand. There you will find the migration, the model, the console command, and a bash script for if you are on Heroku.

Total 1 comment

#13298 report it
oorastard at 2013/05/21 08:21am
Console Applications

Not sure how things will work in Yii 2.0, but I have been using creating Cron Jobs using: http://www.yiiframework.com/doc/guide/1.1/en/topics.console

I use crontab to schedule the Console App to run the command

Leave a comment

Please to leave your comment.

Write new article