CRajesh CRajesh - 5 days ago 5
PHP Question

To add remainder email in yii using crontab

as suggested I created a File MessengerCommand.php under

protected/commands
as

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

$mail=Yii::app()->Smtpmail;
$mail->SetFrom("tsadmin@softthink.com", 'From NAme');
$mail->Subject ="hello";
$mail->MsgHTML("haiii workd");
$mail->AddAddress("rajesh.udutha@itaugments.com", "");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
}else {
echo "Message sent!";
}
}
}


and added
yiic
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

You can use yii console applications to accomplish your task.

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

<?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):
            $this->send($scheduled_record);
        endforeach;
}

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:

<?php
$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.

Comments