How to run a cron job with Yii
Published on 1/25/2011
Sometimes you need to run code on a timer, such as sending out email reminders based on database tables. This is how to do it.
- In /protected/commands, add a file GoCommand.php with this content:
<?php
class GoCommand extends CConsoleCommand
{
public function run($args)
{
echo 'Hello, world';
}
}
?>
- If you want to use your models, components and db connection, in /protected/config/console.php, copy over your ‘import’ and ‘components’ arrays from your main.config:
<?php
// This is the configuration for yiic console application.
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'My Console Application',
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
),
// application components
'components'=>array(
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=my_db',
'emulatePrepare' => true,
'username' => 'root',
'password' => 'password',
'charset' => 'utf8',
'tablePrefix'=>'tbl_',
),
),
);
- then using the command prompt (cmd.exe in Windows), change directories to the protected folder of your web app, and type
yiic Go
and it should run your command.
You can use your models and components and most parts of the Yii framework, but web application stuff won’t work, like sessions.
- In Windows, you can use Task Scheduler to run the PHP file using the command line. Here’s an article on how to do it:
http://www.devx.com/DevX/Article/39900/1763/page/3
... views