linux腳本 直接用cli模式運行腳本


運行方式

/usr/bin/php  /www/wwwroot/run team

意思是,調用PHP路徑,執行wwwroot下的run 文件,去調用team腳本   

通過其中

$_SERVER['argv']函數獲取腳本運行的名稱,來運行某個固定文件夾下的腳本

run 文件:(run 文件沒有后綴名)

#!/usr/bin/env php
<?php
/**
 * 任務計划執行入口
 *
 */
ini_set('log_errors', 0);
define('DYMall', true);

$dir = dirname(__FILE__);
require($dir . '/../global.php');

try {
    $opArr = Command::getParams($_SERVER['argv']);

    if (!@include($dir . '/../library/dymall.php'))
        throw new Exception('dymall.php isn\'t exists!');

    //加載配置
    Command::loadConfig();

    //command 基類
    if (!@include($dir . '/controller/BaseCronCtl.php'))
        throw new Exception("control.php isn't exists!");

    //command file
    if (!@include($dir . '/controller/' . $opArr['file'] . '.php'))
        throw new Exception("{$opArr['file']}.php isn\'t exists!");

    $className = sprintf($opArr['file'] . "%s", 'Ctl');
    $object = new $className();

    $method = $opArr['method'];
    if (!method_exists($object, $method))
        throw new Exception("method {$method} isn't exists", 1);

    $object->$method();

} catch (Exception $e) {
    echo $e->getMessage();
}

class Command
{
    private static $instance = null;

    public function __construct()
    {
        global $setting_config;
        self::parse_conf($setting_config);
        if (function_exists('date_default_timezone_set')) {
            if (is_numeric($setting_config['time_zone'])) {
                @date_default_timezone_set('Asia/Shanghai');
            } else {
                @date_default_timezone_set($setting_config['time_zone']);
            }
        }
    }

    public static function loadConfig()
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private static function parse_conf(&$setting_config)
    {
        $bbc_config = $GLOBALS['config'];
        if (is_array($bbc_config['db']['slave']) && !empty($bbc_config['db']['slave'])) {
            $dbslave = $bbc_config['db']['slave'];
            $sid = array_rand($dbslave);
            $bbc_config['db']['slave'] = $dbslave[$sid];
        } else {
            $bbc_config['db']['slave'] = $bbc_config['db'][1];
        }
        $bbc_config['db']['master'] = $bbc_config['db'][1];
        $setting_config = $bbc_config;
        $setting = ($setting = H('setting')) ? $setting : H('setting', true);
        $setting_config = array_merge_recursive($setting, $bbc_config);
    }

    /**
     * @param $argv
     * @return array
     * @throws Exception
     */
    public static function getParams($argv)
    {
        if (empty($argv[1])) throw new Exception('include_file parameter error');

        isset($argv[2]) ?: array_push($argv, 'index');
        $opArr = [
            'root' => $argv[0],
            'file' => $argv[1],
            'method' => empty($argv[2]) ? 'index' : $argv[2],
        ];

        //取參數
        array_splice($argv, 0, 3);
        array_walk($argv, function ($item) use (&$opArr) {
            list($k, $v) = explode('=', ltrim($item, '--'));
            if (in_array($k, array_keys($opArr)))
                throw new Exception("error param name must no be root、file and method");
            $opArr[$k] = $v;
        });
        //默認插件
        isset($opArr['addon']) ?: $opArr['addon'] = 'pin';
        define('ADDONS_PATH', BASE_ROOT_PATH . '/addons/' . $opArr['addon'] . '/');
        $_GET = $opArr;
        return $opArr;
    }
}

run 原理注釋:

#!/usr/bin/env php 

#!/usr/bin/env php寫法的好處
這種寫法主要是為了讓你的程序在不同的系統上都能適用。

不管你的php是在/usr/bin/php還是/usr/local/bin/php
#!/usr/bin/env php會自動的在你的用戶PATH變量中所定義的目錄中尋找php來執行的

$_SERVER['argv']
該函數

cli模式(命令行)下,第一個參數$_SERVER['argv'][0]是腳本名,其余的是傳遞給腳本的參數,如下圖

代碼:

var_dump(22,$argv,$_SERVER['argv']);exit;

運行:

[root@localhost wwwroot]# php run 22 33
Array
(
[0] => run
[1] => 22
[2] => 33
)

團隊腳本:

#!/bin/bash

# 消耗新注冊用戶綁定邀請關系隊列 實時腳本
max_run_num=7
bin_php="/usr/bin/php"
#線上
#php_file="/www/wwwroot/mall.yaotiao.net/command/run"
#灰度
#php_file="/www/wwwroot/gray.yaotiao.net/command/run"
#測試環境
php_file="/www/wwwroot/test.yaotiao.net/mall4/command/run"

php_command=' team'
script_file=${php_file}${php_command}

if [ ! -f $php_file ]; then
    echo "腳本不存在:$php_file"
    usage
fi

echo "============ "`date +"%Y-%m-%d %H:%M:%S"`" start =============="

running_num=`ps -ef | grep "$script_file" | grep -v 'grep' | wc -l`

while [ $running_num -le $max_run_num ]
do
    if [ $running_num -ge $max_run_num ]; then
        echo "$script_file 正在運行 (進程數:$running_num)"
        break
    else
        echo "啟動進程 (進程數:$running_num)+1"
        DATE=`date +"%Y%m%d"`
    log_file="/data/logs/script/team_$DATE.log"
        $bin_php $script_file >> $log_file 2>&1 &
        running_num=`ps -ef | grep "$script_file" | grep -v 'grep' | wc -l`
    fi
    sleep 1s
done

echo "============ "`date +"%Y-%m-%d %H:%M:%S"`" end ================"

usage() {
    exit 1
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM