Linux的crontab定時任務批量執行PHP腳本

這是要執行的PHP腳本目錄。
要執行的PHP腳本目錄
common中的文件
這裏寫圖片描述
config中的文件
這裏寫圖片描述
db.php

<?php
if($GLOBALS['G_TEST']=='test'){//測試數據庫
    return array(
            's_read' => array('host' => 'localhost', 'user' => '用戶名', 'pwd' => '密碼', 'db' => '數據庫'),
            's_write' => array('host' => 'localhost', 'user' => '用戶名', 'pwd' => '密碼名', 'db' => '數據庫'),
            't_write' => array('host' => 'localhost', 'user' => '用戶名', 'pwd' => '密碼', 'db' => '數據庫')
    );
}else{
    return array(
        's_read' => array('host' => 'localhost', 'user' => '用戶名', 'pwd' => '密碼', 'db' => '數據庫'),
        's_write' => array('host' => 'ip地址', 'user' => '用戶名', 'pwd' => '密碼', 'db' => '數據庫'),
        't_write' => array('host' => 'IP地址', 'user' => '用戶名', 'pwd' => '密碼', 'db' => '數據庫')
    );
}

funs.php函數文件

<?php
defined('_INVALID_') or die('invalid');

function https_request($url, $data = null){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

//優惠券使用通知
function use_coupon_msg($access_token,$openid,$jump_url,$data){
    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
    $template_id = 'MqhVCxK65aOVAGrvcCPcf6QfPNKG3WDlLoH2uBnTag0';
    $message_arr = array(
        'touser' => $openid,
        'template_id' => $template_id,
        'url' => $jump_url,
        "topcolor" => "#667F00",
        "data" => array(
            "first" => array("value" => "已成功使用".$data['first'], "color" => "#173177"),
            "keyword1" => array("value" => $data['key1'].'元進貨紅包', "color" => "#173177"),
            "keyword2" => array("value" => $data['key2'], "color" => "#173177"),
            "keyword3" => array("value" => $data['key3'], "color" => "#173177"),
            "remark" => array("value" => "感謝您的使用,請繼續關注聯盟最新福利!", "color" => "#173177")
        ),
    );
    $tosend_data = json_encode($message_arr);
    https_request($url, $tosend_data);
}

連接數據庫,日誌,發送短信類

<?php
defined('_INVALID_') or die('invalid');
class Db {

    public static function getInstance(){
        return new Db(func_get_args());
    }

    private function getConfig($which){
        $configs = include(CRON_PATH.'config/db.php');
        return $configs[$which];
    }
    private $config;
    private $linkID;

    public function __construct($config){
        $this->config = $this->getConfig($config[0]);
    }

    public function connect() {
        if(empty($this->linkID)){
            $this->linkID = mysqli_connect($this->config['host'], $this->config['user'], $this->config['pwd'], $this->config['db']);
            if(mysqli_connect_errno($this->linkID)){
                exit("Failed to connect to MySQL: " . mysqli_connect_error());
            }
            mysqli_query($this->linkID, "SET NAMES UTF8");
        }
    }

    public function getLink(){
        $this->connect();
        return $this->linkID;
    }

    public function query($sql){
        global $G_TEST;
        if($G_TEST=="test"){
            $sql=str_replace(array('db_正式數據庫','db_正式數據庫'), array('dev_開發數據庫','dev_開發數據庫'), $sql);
        }
        $this->connect();
        $result = mysqli_query($this->linkID, $sql);
        if($result===false){
            echo $this->linkID->errno.': '.$this->linkID->error;
        }elseif($result===true){

        }elseif($result instanceof mysqli_result){
//          mysqli_free_result($result);
        }else{
        }
        return $result;
    }

    public function startTrans(){
        $this->connect();
        mysqli_autocommit($this->linkID, false);
    }

    public function commit(){
        $this->connect();
        mysqli_commit($this->linkID);
        mysqli_autocommit($this->linkID, true);
    }

    public function rollback(){
        $this->connect();
        mysqli_rollback($this->linkID);
        mysqli_autocommit($this->linkID, true);
    }
}


class Log {
    private static $_mtime=0.0;
    public static function owner($log=''){
        global $G_CURFILE;
        $curtime=time();
        $logfile=CRON_PATH.'log/'.$G_CURFILE.date("Ymd",$curtime).'.log';
        file_put_contents($logfile,date("H:i:s",$curtime)."\t".$log."\n",FILE_APPEND);
    }
    public static function runStart(){
        self::$_mtime=microtime(true);
    }
    public static function runEnd($log='',$change=false){
        $mtime=microtime(true);
        $off=round($mtime-self::$_mtime,6);
        if($change){
            self::$_mtime=$mtime;
        }
        self::owner($log.'run:'.$off);
    }

}


class SMS {

    public static function massSMS($mobiles='',$content=''){
        $content = urlencode($content);
        $url = '';//短信接口請求地址
        self::remotedata($url);
    }

    private static function remotedata($url){
        $result = file_get_contents($url);
        if(empty($result)){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $result = curl_exec($ch);
            curl_close($ch);
        }
        return $result;
    }
}
$dbs = array('s_read' => Db::getInstance('s_read'), 's_write' => Db::getInstance('s_write'), 't_write' => Db::getInstance('t_write'));

公用執行入口文件index.php

<?php
ini_set("display_errors", "On");
error_reporting(E_ALL);
set_time_limit(3600);
date_default_timezone_set('Asia/Shanghai');
header("content-type:text/html; charset=utf-8");

define('_INVALID_', 1);
define('CRON_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
//$argv爲PHP執行命令行特殊變量,是一個以數字爲鍵的一維數組 $argv[0]爲要執行的文件 $argv[1]以後是文件後帶的參數。還有一個類似的變量$argc表示命令行總的參數的個數。熟悉C語言的同學們應該比較瞭解這兩個變量。
$G_FLAG=isset($argv[1]) && !empty($argv[1]) ? $argv[1] : '';
$G_TEST=isset($argv[2]) && !empty($argv[2]) ? $argv[2] : '';
$G_CURFILE='';
include('common/funs.php');
include('common/utils.php');
foreach(glob(__DIR__.'/auto_*.php') as $stat_file){
    $G_CURFILE=substr(basename($stat_file,".php"),5);
    Log::runStart();
    runStat($stat_file);
}

function runStat($file){
    global $G_FLAG,$dbs;
    require_once $file;    
}

舉一個簡單的執行腳本

<?php
defined('_INVALID_') or die('invalid');

if($G_FLAG != 'userCountPerHour'){
    return;
}
$curtime = time();
$etime = strtotime(date('Y-m-d'));
$stime = $etime - 86400;
$result = $dbs['s_read']->query("select constype,count(*) as ct from `數據表` where constype in (12,13) and ctime >= $stime and ctime < $etime group by constype");
if($result){
    while($row = mysqli_fetch_assoc($result)){
        if($row['constype'] == 12){
            $lostNum = $row['ct'];
        }
        if($row['constype'] == 13){
            $newNum = $row['ct'];
        }
    }
    mysqli_free_result($result);
}
$total = $dbs['s_read']->query("select count(*) as ct from `數據表` where idtype = 0 group by idtype");
if($total){
    while($row = mysqli_fetch_assoc($total)){
        $bondTotal = $row['ct'];
    }
    mysqli_free_result($total);
}
$lostNum = empty($lostNum) ? 0 : intval($lostNum);
$newNum = empty($newNum) ? 0 : intval($newNum);
$bondTotal = empty($bondTotal) ? 0 : intval($bondTotal);
$dataStr = '('.$newNum.','.$lostNum.','.($newNum-$lostNum).','.$bondTotal.',"'.date('Y-m-d',$stime).'",'.$curtime.')';
$addResult = $dbs['s_write']->query("insert into `數據表` values $dataStr");

crontab任務執行實例

#1 0 * * * /usr/bin/php /data/cron/StatCron/index.php userCountPerHour//每小時執行一次該文件
發佈了28 篇原創文章 · 獲贊 17 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章