CRajesh CRajesh - 10 months ago 51
PHP Question

To add remainder email in yii using crontab

as suggested I created a File MessengerCommand.php under


class MessengerCommand extends CConsoleCommand
public function run($args)
/* if(ERunActions::runBackground())
{ */

$mail->SetFrom("", 'From NAme');
$mail->Subject ="hello";
$mail->MsgHTML("haiii workd");
$mail->AddAddress("", "");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}else {
echo "Message sent!";

and added
command as

$path = dirname(__FILE__);
//echo $path;
shell_exec( $path . "/protected/yiic messenger" );

and it will trigger email when I load the site ....

but I dont wanna refresh the site ..I need to make this to run in background ..Please help me.

Answer Source

You can use yii console applications to accomplish your task.

In protected/commands create a new file with Command sufix, for example: MessengerCommand.php:

class MessengerCommand extends CConsoleCommand

In class MessengerCommand you have several options to create the command action. In this sample we will override run method:

public function run($args)
        $birth_month = date("m");
        $birth_day = date("d");
        $criteria = new CDbCriteria;
        $criteria->condition = "birth_month = $birth_month and birth_day = $birth_day";
        $listScheduledRecords = Table::model()->findAll($criteria);
        foreach($listScheduledRecords as $scheduled_record):

public function send($scheduled_record)
    your logic to send your email

In protected dir, create a file: messenger.php. This file will be the command executer:

$path = dirname(__FILE__);
$output = shell_exec( $path . "/./yiic messenger" );
echo $output;

To test it, on Linux/Unix, run in console/terminal:

cd /.../.../...your_protected_path 
php messenger.php

To test on Windows, you need to refer to your php.exe location path or set php.exe on your system environment variables and use yiic equivalence for Windows

To schedule automatic task, in this sample, daily execution, on Linux/Unix, you can use cron jobs:

In console/terminal:

crontab -e

In cron file, add the scheduled task, daily, at 9h00. Remember cron sintax: # minute hour day of month month day of week command

0   9  *  *  * php /full_path/protected/messenger.php

Save file and exit.

To schedule automatic task on Windows, refer to their docs / help on Internet.

If you have errors, Yii Console applications use their own config file (protected/config/console.php). Common mistakes are wrong db connection, components, modules in protected/config/console.php.