How to: Cron Jobs

Hey guys,

I’m trying to figure out how to write the code to run a cron job that executes a controller function.

Is this possible?

I am unsure what to include at the top of the php file etc. I’ve checked out index.php but am not sure if “Yii::createWebApplication($config)->run();” should be included etc.

Cheers,

Sn0rcha

Did you check out http://www.yiiframework.com/doc/guide/topics.console ?

It’s probably not a good idea to call a controller action from a console command. Think about it: a controller is part of a web application (so might e.g. use $_GET, $_POST, $_SESSION, …) which don’t contain anything useful in a console application.

Thanks mike didn’t even see that part of the documentation :))

You’re a gentleman and a scholar!

any examples on a working Console Application?

You’re welcome, sn0rcha :).

@bettor:

What are you missing from the guide page above? You can do mostly anything in a console app, you would do in a controller action (except request and session based things like user auth…).

So you can access Yii::app()->db or do queries with AR.

Do I need to have a seperate config file and models for console applications as when I use the same config file as the web I get the following error;


exception 'CException' with message 'Property "CConsoleApplication.theme" is not defined.' in /var/www/yii/framework/base/CComponent.php:173



If I have to have seperate files/models for console and web wouldn’t it be easier just to write straight php/mysql???

Cheers,

Sn0rcha

You need different config-files since CWebApplication and CConsoleApplication differ.

You only need different configs. You can use same models and so on.

I suggest to create a shared config file where you define all things needed in console and web-application (eg logging, components and so on). In the entry script you can then merge the configs. I do this:




require(__DIR__ . '/framework/yii.php');

$config = include(__DIR__ . '/application/config/shared.php');


if (!isset($_SERVER['SERVER_NAME']))

{

	Yii::createConsoleApplication(CMap::mergeArray($config, include(__DIR__ . '/application/config/console.php')))->run();	

}

else

{

	Yii::createWebApplication(CMap::mergeArray($config, include(__DIR__ . '/application/config/web.php')))->run();

}



thanks for the help :)

Hi guys,

I am having an issue while trying to execute the cron command. Below is the error:

PHP Warning: CApplication::require(protected/config/main.php): failed to open stream: No such file or directory in /var/www/vhosts/beta/framework/base/CApplication.php on line 100

PHP Fatal error: CApplication::require(): Failed opening required ‘protected/config/main.php’ (include_path=’.:/usr/share/pear:/usr/share/php’) in /var/www/vhosts/beta/framework/base/CApplication.php on line 100

I have no idea what’s this mean, could anybody please explain ? I am sure that the main.php is already in the protected/config folder, since I have another web application running under index.php.

Thank you very much!

@revo110:

Can you explain a little more, how you created your command and how you run it?

Hi Mike,

Thanks for the response…I have followed the link you gave above:

http://www.yiiframework.com/doc/guide/topics.console

And I don’t know where I made mistakes ? Those errors are just showed up.

Thanks!

Did you check if this file is present (in your applications directory tree)

/Tommy

Thanks for your reply, but do you read my question ? I have explained it that I am sure that the main.php is already in the protected/config folder.

You still didn’t give any details, so please help us help you. What did you do? Create a yiic command? Create a pure console script…? What exactly do you type, before the error appears…? So many questions are open :)

Hi Mike,

Okay, here you go:

First, I created a bootstrap file console.php for the console application:


<?php

//remove the following line in production mode

defined('YII_DEBUG') or define('YII_DEBUG', true);


//include the bootstrap file

require_once('framework'.DIRECTORY_SEPARATOR.'yii.php');


$configFile = 'protected'.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'main.php';


//create console application instance and run

Yii::createConsoleApplication($configFile)->run();

And then, I created the ImageCacheCleanerCommand.php and stored it under protected/commands folder:


<?php


class ImageCacheCleanerCommand extends CConsoleCommand {


    public function getHelp()

    {

        echo "Delete the image cache that has not being used";

    }

    

    public function run($args)

    {

        $path = Yii::app()->getAssetManager()->basePath.DIRECTORY_SEPARATOR.'vendors'.DIRECTORY_SEPARATOR.'image-1.4.1'.DIRECTORY_SEPARATOR.'imagecache';


        if (file_exists($path) && is_dir($path))

        {

            $dir = opendir($path);

            while ($file = readdir($dir))

            {

                $pattern = '/.{1}html/';

                $match = preg_match($pattern, $file);

                if (!$match)

                {

                    if (is_file($path.DIRECTORY_SEPARATOR.$file)) {

                        if (!is_writeable($path.DIRECTORY_SEPARATOR.$file)) {

                            $chmoded = chmod($path.DIRECTORY_SEPARATOR.$file, 0644);

                        }

                        unlink($path.DIRECTORY_SEPARATOR.$file);

                    }


                }

            }

            closedir($dir);

        }        

    }

}



And, I tried to execute it in linux command:


$ /usr/bin/php  /var/www/vhosts/beta/console.php imagecachecleaner

And next, I got this error:


PHP Warning:  CApplication::require(protected/config/main.php): failed to open stream: No such file or directory in /var/www/vhosts/beta/framework/base/CApplication.php on line 100

PHP Fatal error:  CApplication::require(): Failed opening required 'protected/config/main.php' (include_path='.:/usr/share/pear:/usr/share/php') in /var/www/vhosts/beta/framework/base/CApplication.php on line 100

Okay, I hope that is details enough…thanks!

Ok, first: You don’t neccessarily need your bootstrap file. Using yiic is much more convenient to run the commands you put into protected/commands. It also integrates better with your application:


./protected/yiic imageCacheCleaner arg1 arg2 ...

This command will use protected/config/console.php as default config file since web config can differ from console config. So you only have to make sure, you have the right configuration there (maybe share the db connection part).

Hi again and thanks for the reply, and please don’t get bored answering me hehehe.

Ok first the details:

I created a console.php config in the protected/config folder, and looks like this:


<?php


return array(


    'import'=>array(

	    'application.commands.*',

	),

	

	'components' => array(


	   'db'=> array(

                        // uncomment the following to use MySQL as database

                        'class' 		=> 'CDbConnection',

                        'connectionString'	=> 'mysql:host=localhost;dbname=grup',

                        'charset' 		=> 'utf8',

                        'username'		=> 'user',

                        'password'              => 'pass',

                        'emulatePrepare'        => true,

                        'schemaCachingDuration' => 3600,

		),

	),

);

Then, using the command line, I executed:


C:\xampp\php\php.exe yiic imageCacheCleaner

I have tried using the yiic command as you advised, and as you can see in the screenshot within the attachment, it does nothing. I have checked the folder where the image caches are stored and there are still caches.

Could you please tell me what has happened ? Is it because incorrect path to imageCacheCleaner ?

Thanks!

You should better run the yiic command that is inside your protected folder. And you should maybe first cd to the folder where your application’s index.php resides.

Nope, still does not work. How do you usually do your cron job ?

Store the console command in protected/commands.

/Tommy