Sometimes, an application requires some background tasks such as re-generating a sitemap or refreshing statistics. A common way to implement this is by using cron jobs. When using Yii, there are two ways to do this, which are as follows:
In this recipe, we will see how to implement both. For our recipe, we will implement writing the current timestamp into a timestamp.txt
file under the protected
directory.
Carry out the following steps:
protected/controllers/CronController.php
as follows:<?php class CronController extends CController { public function actionIndex() { $filename = Yii::getPathOfAlias("application")."/timestamp.txt"; file_put_contents($filename, time()); } }
crontab
file:GET http://example.com/index.php?r=cron wget -O - http://example.com/index.php?r=cron lynx --dump http://example.com/index.php?r=cron >/dev/null
protected/commands/CronCommand.php
as follows:<?php class CronCommand extends CConsoleCommand { public function run($args) { $filename = Yii::getPathOfAlias("application")."/timestamp.txt"; file_put_contents($filename, time()); } }
crontab
file to execute it:/path/to/./yiic cron
GET
, wget
, and lynx
fetch a page through HTTP, so we can use these to trigger the normal web application execution. This method has its pros and cons. The main pro is that we are executing a web application, so the environment is the same as in all other application parts. The main con is that it is not completely secure. Even if we use the $_GET
variable as a password, there is no guarantee that it will remain undisclosed forever.
The second method is much more secure because the console command can be executed only if one has SSH access to the server. The con is that the environment is different from the web application.
Another way to solve a problem is to use a message queue. Most implementations will deal with concurrency issues for you and will allow you to do the processing almost immediately if there are not too many requests. Implementations to check are:
In order to learn more about Yii console applications, refer to the following URL:
3.138.200.66