[PHP] 命令行执行整合pathinfo模拟定时任务

命令行模式下,根据传参,调用不同控制器。控制器中根据配置定时执行指定方法

Application.php

<?php
class Application{
    public static function main(){
        header("content-type:text/html;charset=utf-8");
        self::register();
        self::commandLine();
        self::pathInfo();
    }
    //自动加载
    public static function loadClass($class){
        $class=str_replace(‘\\‘, ‘/‘, $class);
        $dir=str_replace(‘\\‘, ‘/‘, __DIR__);
        $class=$dir."/".$class.".php";
        require_once $class;
    }
    //命令行下
    public static function commandLine(){
        if(php_sapi_name()=="cli"){
            $_SERVER[‘PATH_INFO‘]="";
            foreach ($_SERVER[‘argv‘] as $k=>$v) {
                if($k==0) continue;
                $_SERVER[‘PATH_INFO‘].="/".$v;
            }
        }
    }
    //pathinfo处理
    public static function pathInfo(){
        if(isset($_SERVER[‘PATH_INFO‘])){
            $pathinfo=array_filter(explode("/", $_SERVER[‘PATH_INFO‘]));
            for($i=1;$i<=count($pathinfo);$i++){
                $key=isset($pathinfo[$i]) ? $pathinfo[$i] : ‘‘;
                $value=isset($pathinfo[$i+1]) ? $pathinfo[$i+1] :"";
                switch ($i) {
                    case 1:
                        $_GET[‘m‘]=ucfirst($key);
                        break;
                    case 2:
                        $_GET[‘c‘]=ucfirst($key);
                        break;
                    case 3:
                        $_GET[‘a‘]=$key;
                        break;
                    default:
                        if($i>3){
                            if($i%2==0){
                                $_GET[$key]=$value;
                            }
                        }
                        break;
                }
            }
        }
        $_GET[‘m‘]=!empty($_GET[‘m‘]) ? ucfirst($_GET[‘m‘]) : ‘Index‘;
        $_GET[‘c‘]=!empty($_GET[‘c‘]) ? ucfirst($_GET[‘c‘]) : ‘Index‘;
        $_GET[‘a‘]=!empty($_GET[‘a‘]) ? $_GET[‘a‘] : ‘index‘;
        $class="\\Controller\\{$_GET[‘m‘]}\\{$_GET[‘c‘]}";
        $controller=new $class;
        $controller->$_GET[‘a‘]();
    }
    //致命错误回调
    public static function shutdownCallback(){
        $e=error_get_last();
        if(!$e) return;
        self::errorHandler($e[‘type‘],‘<font color="red">Fatal Error</font> ‘.$e[‘message‘],$e[‘file‘],$e[‘line‘]);
    }
    //错误处理
    protected static function myErrorHandler($errno,$errstr,$errfile,$errline){
        list($micseconds,$seconds)=explode(" ",microtime());
        $micseconds=round($micseconds*1000);
        $micseconds=strlen($micseconds)==1 ? ‘0‘.$micseconds : $micseconds;
        if(php_sapi_name()=="cli"){
            $break="\r\n";
        }else{
            $break="<br/>";
        }
        $mes="[".date("Y-m-d H:i:s",$seconds).":{$micseconds}] ".$errfile." ".$errline." line ".$errstr.$break;
        echo $mes;
    }
    //注册
    public static function register(){
        error_reporting(0);
        set_error_handler(function($errno,$errstr,$errfile,$errline){
            self::myErrorHandler($errno,$errstr,$errfile,$errline);
        });
        register_shutdown_function(function(){
            self::shutdownCallback();
        });
        spl_autoload_register("self::loadClass");
    }
}

Application::main();

\Controller\Client\Cron.php

<?php
namespace Controller\Client;

class Cron{
    private $second=0;
    private $tasks=array(
        array("duration"=>5,"method"=>"doSomething"),
        array("duration"=>2,"method"=>"doSomething2"),
    );
    public function index(){
        while (true) {
            sleep(1);
            $this->second++;
            foreach($this->tasks as $task){
                if($this->second%$task[‘duration‘]==0){
                    $this->$task[‘method‘]();
                }
            }
        }
    }
    public function doSomething(){
        echo "[".date("Y-m-d H:i:s",time())."] doSomething1 ok!\r\n";
    }
    public function doSomething2(){
        echo "[".date("Y-m-d H:i:s",time())."] doSomething2 ok!\r\n";
    }
}

效果:

方法doSomething每隔2秒执行一次

方法doSomething2每隔5秒执行一次

现在执行其他方法是同步的,可以再优化成开新线程执行这些方法,就不会阻塞主线程的定时了

时间: 2024-08-07 08:54:00

[PHP] 命令行执行整合pathinfo模拟定时任务的相关文章

编码用命令行执行的C语言词语统计程序

需求介绍 程序处理用户需求的模式为: wc.exe [parameter][filename] 在[parameter]中,用户通过输入参数与程序交互,需实现的功能如下: 1.基本功能 支持 -c  统计文件字符数 支持 -w 统计文件单词数 支持 -l  统计文件总行数 2.拓展功能 支持 -a 返回高级选项(代码行 空行 注释行) 支持 -s 递归处理符合条件的文件 3.高级功能 支持 -x 程序以图形界面与用户交互 [filename] 是待处理文件名. 设计历程及感想 初次看到这个题目,

命令行执行python模块时提示包找不到的问题

庄稼人不是专职python开发的道友,虽然与python相识已多年,可惜相识不相知,只是偶尔借助pydev写一些简单的小工具. 多年来,一直困惑于这样一个问题:同样的工程,同样的代码,使用pydev可以运行任意一个python脚本,而使用命令行运行却不行?命令行下(或者双击执行)总是提示"ImportError: No module named xxx"?pydev究竟做了什么魔术呢? 长话短说,以上面工程为例,如果是在命令行中直接执行 python c.py , 都会提示"

IT忍者神龟之命令行执行java程序

第一:简单的命令行(没有package) c:/temp/bin/GetGreeting.java [java] view plaincopy public class GetGreeting { public static void main(String [] args) { System.out.println("Hello world"); } } 1.编译:cmd--cd到c:/temp/bin  javac GetGreeting.java 生成GetGreeting.cl

java工程打成jar包在命令行执行运行缓慢问题解决

一个普通的java工程,用cxf连接webserivice.在eclipse下运行正常,但用eclipse达成jar包,在命令行执行却异常缓慢. 通过一些尝试,发现是因为打包的方式不对.eclipse导出可运行jar包有三种方式,分别为: 1.Extract required libraries into generated JAR 2.Package required libraries into generated JAR 3.Copy required libraries into  a

PHP下的命令行执行

PHP 的命令行模式 以下是 PHP 二进制文件(即 php.exe 程序)提供的命令行模式的选项参数,您随时可以通过 PHP -h 命令来查询这些参数. Usage: php [options] [-f] <file> [args...] php [options] -r <code> [args...] php [options] [-- args...] -s Display colour syntax highlighted source. -w Display sourc

关于jmeter命令行执行.jmx文件出现Error in NonGUIDriver java.lang.RuntimeException: Could not find the TestPlan class的问题

jmeter命令行执行.jmx文件时,有时回出现Error in NonGUIDriver java.lang.RuntimeException: Could not find the TestPlan class的错误 目前出现此错误的原因是在jmeter3.0及以下版本存在bug 对于使用UI界面生成.jmx时,请在testplan层做保存,而非在threads层做保存,如下图

从命令行执行django数据库操作

从命令行执行django数据库操作,报错: django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_INDEX_TABLESPACE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before

Java命令行执行参数中包含空格被截断的问题解决

使用java -jar命令在命令行执行jar包,传入参数时,参数包含空格,例如“hello world”,这个参数会被解析成两个参数“hello”和“world”.这样的结果是执行时不能正常的获取参数.这时只要在参数两边加上引号即可. 一开始使用的命令如下:java -jar Test.jar %{test}   —— %{test}为其他程序中传入的参数 修改之后的命令如下:java -jar Test.jar ‘%{test}‘  这样就可以作为一个参数获取值了

解决命令行执行shell脚本成功,但crontab执行失败

实际生产案例 生产机房自建PPTP客户端通过拨号连接到生产机房,但是一旦客户端网络是意外断线再重新拨号 会产生IP冲突,于是写了一个脚本监控PPTP的IP是否有多个(一般冲突以后会生成2个IP) #!/bin/bash #author Liuyueming . /etc/profile #开始没有加这个环境变量 for i in {10..35} do n=`ifconfig|grep 10.13.0.${i}|wc -l` #循环取ip并计数 # echo `ifconfig|grep 10.