Cron Jobs in Yii

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

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.

2 0
9 followers
Viewed: 35 102 times
Version: Unknown (update)
Category: How-tos
Written by: aarondfrancis
Last updated by: Roman Solomatin
Created on: May 6, 2013
Last updated: 9 years ago
Update Article

Revisions

View all history

Related Articles