Use Cronjobs in Linux to automate Yii console tasks

Source: Internet
Author: User
Use Cronjobs in Linux to automate Yii console tasks

This article describes how to use Cron jobs in Linux to automate the execution of Yii Console Application (Console) tasks, such as cache cleanup, temporary file cleanup, email sending, and website backup every night, repetitive work is done at the backend of the server. Yii itself provides powerful support and we do very little. when yiic webapp is used to automatically generate a project structure, the powerful Yii has all helped us generate it. it only takes three steps.

1.Configure the components required in product/config/console. php, Such as database connection

'db'=>array(    'connectionString' => 'mysql:host=localhost;dbname=testdrive',    'emulatePrepare' => true,    'username' => 'root',    'password' => '',),

2. inherit from CConsoleCommand to write your own command class.

Yii provides two methods for execution. if you execute a single taskRunThe other method is similar to the Action in the Controller.ActionXXX, InFramework/consoleMany instances are provided for our reference. For example, CHelpCommand directly uses run:

class CHelpCommand extends CConsoleCommand{    /**     * Execute the action.     * @param array $args command line parameters specific for this command     */    public function run($args)    {        $runner=$this->getCommandRunner();        $commands=$runner->commands;        if(isset($args[0]))            $name=strtolower($args[0]);        if(!isset($args[0]) || !isset($commands[$name]))        {            if(!emptyempty($commands))            {                echo "Yii command runner (based on Yii v".Yii::getVersion().")\n";                echo "Usage: ".$runner->getScriptName()." 
 
   [parameters...]\n";                echo "\nThe following commands are available:\n";                $commandNames=array_keys($commands);                sort($commandNames);                echo ' - '.implode("\n - ",$commandNames);                echo "\n\nTo see individual command help, use the following:\n";                echo "   ".$runner->getScriptName()." help 
  
   \n";             }else{                echo "No available commands.\n";                echo "Please define them under the following directory:\n";                echo "\t".Yii::app()->getCommandPath()."\n";             }         }else            echo $runner->createCommand($name)->getHelp();    }    /**     * Provides the command description.     * @return string the command description.     */    public function getHelp()    {        return parent::getHelp().' [command-name]';    }}
  
 

UseActionRun the cleanup command

Class CleanupCommand extends CConsoleCommand {private $ sessionTableName = 'It _ common_session ';/*** automatically clears sessions every 2 minutes. */public function actionSession () {$ now = time (); $ SQL = "DELETE FROM {$ this-> sessionTableName} WHERE lastactivity <$ now"; $ command = Yii:: app ()-> db-> createCommand ($ SQL); $ command-> execute ();}/*** clear the system cache, every morning at */public function actionCache () {Yii: app ()-> cache-> flush (); Yii: app () -> dbcache-> flush (); Yii: app ()-> fcache-> flush ();}/*** clear Upload temporary file */public function actionTempfiles () {$ dir = Yii: getPathOfAlias ('site. frontend. www. uploads. temp '). '/'; foreach (glob ($ dir. '*. * ') as $ v) {unlink ($ v );}}}

3.Use Linux commands ,? Vi crontab-e? Open the automatic execution tab and add a line

30 2 * * * php /path/to/console.php cleanup xxx >> /path/to/logfile

You need to create console. php at the same level as the entry file in the Yii application directory:

 

The above means that the cleanup task is automatically executed at two o'clock every night, and a powerful automated function task is completed in just a few steps. Is it simple enough?

FAQs:

1) If crontab is not automatically executed, check whether your syntax is correct.

2). OKProtected/yiic? Does the file have the execution permission?Chmod + x yiic? Authorization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.