YII console 定时脚本

本文详细介绍了在Linux和MacOS环境下如何使用yiic命令进行定时程序配置及命令行操作,包括设置执行权限、指定PHP路径、使用命令配置文件等步骤,并提供了实例代码演示如何执行单一任务和使用命令行实现定时任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

可以用来做定时程序通过命令运行代码,非url访问方式更安全

入口文件

新建cron.php内容如下

<?php

$yii = '/home/apps/framework/yii.php';
require_once($yii);
$configFile = dirname(__FILE__).'/../config/console.php'; //区别1
Yii::createConsoleApplication($config)->run(); //区别2
  • 1.这里是createConsoleApplication
  • 2.控制台的命令配置文件是 protected/config/console.php 文件

多任务

系统默认的路径是protected/commands/shell 如果你执行单一的任务,直接在run方法里面写,另外一种就是同写你的Controller(控制器),前面增加actionXXX

protected/extensions/clean_command/ECleanCommand.php

<?php
class ECleanCommand extends CConsoleCommand
{
	public $webRoot = null;
	public function getHelp()
	{
		$out = "Clean command allows you to clean up various temporary data Yii and an application are generating.\n\n";
		return $out.parent::getHelp();
	}
	public function actionCache()
	{
		$cache=Yii::app()->getComponent('cache');
		if($cache!==null){
			$cache->flush();
			echo "Done.\n";
		}
		else {
			echo "Please configure cache component.\n";
		}
	}
	public function actionAssets()
	{
		if(empty($this->webRoot))
		{
			echo "Please specify a path to webRoot in command properties.\n";
			Yii::app()->end();
		}
		$this->cleanDir($this->webRoot.'/assets');
		echo "Done.\n";
	}
	public function actionRuntime()
	{
		$this->cleanDir(Yii::app()->getRuntimePath());
		echo "Done.\n";
	}
	private function cleanDir($dir)
	{
		$di = new DirectoryIterator ($dir);
		foreach($di as $d)
		{
			if(!$d->isDot())
			{
				echo "Removed ".$d->getPathname()."\n";
				$this->removeDirRecursive($d->getPathname());
			}
		}
	}
	private function removeDirRecursive($dir)
	{
		$files = glob($dir.'*', GLOB_MARK);
		foreach ($files as $file)
		{
			if (is_dir($file))
			$this->removeDirRecursive($file);
			else
			unlink($file);
		}
		if (is_dir($dir))
		rmdir($dir);
	}
}

 console.php,commandMap配置中需要加入编写的命令文件

<?php

// This is the configuration for yiic console application.
// Any writable CConsoleApplication properties can be configured here.
return array(
    'basePath' => dirname(__FILE__) . DIRECTORY_SEPARATOR . '..',
    'name' => 'My Console Application',
    'import'=>array( //可以使用model等
        'application.models.*',
        'application.components.*',
    ),
    'components'=>array( 
        'db'=>require(dirname(__FILE__) . '/db.php')
    ),
    'commandMap' => array(
        'clean' => array(
            'class' => 'ext.clean_command.ECleanCommand',
            'webRoot' => 'E:\Apache2\htdocs\webapp', //注意修改 class::webRoot
        ),
        'rbac' => array(
            'class' => 'application.commands.shell.RbacCommand',
        )
    ),
);

命令行运行cd E:\Apache2\htdocs\webapp\protected\进入cron.php的目录

 执行命令

php cron.php clean

提示下面:说明可以使用3个命令

Usage: E:\Apache2\htdocs\webapp\protected\php cron.php clean <action>
Actions:
    cache
    assets
    runtime

php cron.php clean runtime

E:\Apache2\htdocs\webapp\protected>php cron.php clean assets
Removed E:\Apache2\htdocs\webapp/assets\1f5cfc05
Removed E:\Apache2\htdocs\webapp/assets\836290cc
Done.

单一任务

<?php
class TestCommand extends CConsoleCommand
{
	public function getHelp()
	{
        //php.exe crons.php help test
	    return '这里显示命令的帮助信息';
	}

	/**
	 * Execute the action.
	 * @param array command line parameters specific for this command
	 */
	public function run($args)
	{
		if(!isset($args[0]))
			$this->usageError('请输入参数.');
		echo('你输入的参数是 :\n');
		var_dump($args);
		return 1; #必须返回数字
	}
}
php cron.php test p1 p2 p3

你输入的参数是 :\narray(3) {
  [0]=>string(2) "p1"
  [1]=>string(2) "p2"
  [2]=>string(2) "p3"
}

 单任务带参数

    public function actionRun($oldUserId, $newUserId)
    {
        if (!$oldUserId || !$newUserId) {
            echo "请输入用户ID\n";
            return;
        }

//run --oldUserId=value --newUserId=value

查询数据库

   public function actionIndex()
   {
       try {
           $db = Yii::app()->db;
           $sql = "SELECT * FROM your_table_name";
           $results = $db->createCommand($sql)->queryAll();
           //Member::model()->findAll($criteria);
           foreach ($results as $row) {
               print_r($row);
           }
       } catch (Exception $e) {
           echo "Error: " . $e->getMessage();
       }
   }
   

yii crontab作业

yii console command 控制台命令,实现定时任务。当然,这得结合系统,如XP的计划任务,linux的crontab命令 vim /etc/crontab

##然后输入
1 * * * *  php /具体地址/protected/cron.php Test >>/具体地址/protected/commands/test.log

'CException' with message 'Property "CConsoleApplication.user" is not defined.' 在console程序中不能用CWebUser,shell程序中调用到Yii::app()->user会报错


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值