PHP脚本重新运行自己直到进程完成。然后每周重新启动

时间:2014-11-05 08:56:11

标签: javascript php web-services cron automatic-updates

我制作了一个从Web服务中检索XML内容的脚本。该过程需要每周运行一次,但脚本本身需要重新运行大约180次才能完成该过程。每次运行脚本大约需要3-8分钟。我希望它在每次完成后重新运行约5秒钟。

我目前的解决方案是:

  • Windows的任务计划程序每周打开一次php页面。
  • 当脚本运行并完成时,javascript会在完成后5秒重启页面。
  • 当脚本的最后一次运行时,它会删除页面的重新加载以使其停止。

此解决方案的问题在于它每周都会打开一个新的浏览器窗口。有没有什么好的替代方法可以做到这一点,而无需手动关闭浏览器?

重新运行脚本的原因是由于php服务器最大限制的脚本超时设置,以及每次运行后查看状态是否发生错误的可能性。

我没有使用cron,因为它需要进行非常多的轮询才能让进程在上次运行的5秒内启动。对于脚本的每周启动,我认为只要脚本使用javascript重新运行它就不会起作用吗?

1 个答案:

答案 0 :(得分:0)

使用PHP:

<?php

// increase the maximum execution time to 43200 seconds (12 hours)
set_time_limit(43200);

function runTask() {
    static $cycles = 0;

    // do whatever you need to do

    // Increments cycle count then compares against limit
    if ($cycles++ < 180)  {
        sleep(5);  // wait five seconds
        runTask(); // run it again
    }
}

runTask(); // fire up the loop

或者,如果您是Javascript的粉丝......

使用node.js:

var cycles = 0;

function runTask() {
  // do whatever you need to do

  // Increments cycle count then compares against limit
  if (cycles++ < 180) {
    setTimeout(runTask, 5000); // run again in 5000 milliseconds
  }
}

runTask(); // fire up the loop

两次解决方案都不会再次运行该函数,直到每次迭代完成后5秒。

让你的任务运行器直接执行任一脚本;不需要浏览器。