【问题标题】:Executing a php script in order按顺序执行php脚本
【发布时间】:2014-07-05 13:45:03
【问题描述】:

我有多个当前正在运行的 php 脚本。我创建了一个 cron 作业来在给定时间执行所有脚本。但是现在客户想要一个触发器/事件类型,以便他可以执行这些脚本。所以我想到了使用 exec 函数。

所以问题来了,这些脚本必须按顺序执行。例如:我有 2 个脚本,即 step1.php 和 step2.php。如何在后台进程中依次运行2个php脚本。

我读到在 exec 函数中使用第三个参数可以返回一个结果,但它总是给我一个结果:string(0) ""

This is what I want to achieve:
$step1 =  exec("php step1.php > /dev/null &", $output, $returnVal);
if($step1 === TRUE) exec("php step2.php > /dev/null &", $output, $returnVal);

或者也许他们的另一个 php 函数比使用 exec 更合适???真的不知道。请帮忙

非常感谢大家

【问题讨论】:

    标签: php exec background-process


    【解决方案1】:

    您不必从 php 脚本运行 exec() 来处理其他 php 脚本中的代码。可能有十几种方法可以做你想做的事,但我可能会使用一种:

    将step1.php和step2.php中的代码功能化:

    旧(伪):

    <?php
        $var = true;
        return $var;
    ?>
    

    新:

    <?php
        function foo() {
            $var = true;
            return $var;
        }
    ?>
    

    包括那些脚本(因为代码现在已功能化,在您调用函数之前它不会被执行)。因此,在调用步骤脚本的脚本中:

    <?php 
        include('step1.php');
        include('step2.php');  
    ?>
    

    现在用你需要的任何逻辑调用你需要的函数:

    <?php
        include('step1.php');
        include('step2.php');
    
        if(foo() == true) {
            bar(); //bar() is found in step2.php
        }
    ?>
    

    同样,有几种方法可以实现这一点,很大程度上取决于您的要求以及步骤 php 脚本中的代码正在做什么。鉴于缺乏关于 step1 和 step2 尝试执行的细节的详细信息,我对此做出了假设。

    【讨论】:

      【解决方案2】:

      在第一个脚本的末尾调用第二个脚本。

      if (... == TRUE) {
        include('second_script.php');
      }
      

      然后你只需要在 cron 上运行第一个脚本。

      【讨论】:

      • 嗨,Johan,首先感谢您抽出宝贵时间。 :)。但如果我只包含脚本,它就不会在后台运行。
      • 我的意思是这样的:$result = exec("php two_scripts.php &gt; /dev/null &amp;", $output); 所以你不需要检查返回值。
      【解决方案3】:

      假设你有 step1.php 输出 true 成功

      $step1 =  exec("php step1.php > /dev/null &", $output, $returnVal);
      

      $step1 现在是命令结果的最后一行。

      [编辑:误读了手册。根据您的需要,您可能确实需要检查 $step1 的输出结果,并且您得到一个空字符串,因为您没有在 step1.php 脚本中输出任何内容?然而,其他一切似乎都是正确的。]

      您应该检查的是$returnVal 的返回状态。这个变量是通过引用传递的(根据手册),所以你的代码应该是:

      exec("php step1.php > /dev/null &", $output, $returnVal);
      if($returnVal === TRUE) exec("php step2.php > /dev/null &", $output, $returnVal);
      if($returnVal === TRUE) exec("php step3.php > /dev/null &", $output, $returnVal);
      

      您甚至可以使用 while 循环:

      $num_steps = 4; //Arbitrary number for example
      $step = 1;
      
      while($returnVal === TRUE && $i <= $num_steps) {
      
          exec('php step'.$step.'.php > /dev/null &', $output, $returnVal);
          $i++;
      }
      

      [小心,以上我没有测试过,可能不适合你想做的事情]

      编辑:下面的 islanddave 的回答是“更好”。我假设您当前的流程已设置,并且您无法更改它(例如,您拥有的时间量,由于遗留原因无法重构现有代码等)。

      【讨论】:

        猜你喜欢
        • 2012-11-23
        • 1970-01-01
        • 2015-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-26
        • 2011-10-26
        • 2017-04-06
        相关资源
        最近更新 更多