Linux的crontab定时任务批量执行PHP脚本

这是要执行的PHP脚本目录。
Linux的crontab定时任务批量执行PHP脚本_第1张图片
common中的文件
Linux的crontab定时任务批量执行PHP脚本_第2张图片
config中的文件
Linux的crontab定时任务批量执行PHP脚本_第3张图片
db.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函数文件


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);
}

连接数据库,日志,发送短信类


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


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;    
}

举一个简单的执行脚本

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//每小时执行一次该文件

你可能感兴趣的:(Linux,PHP)