首页 > 解决方案 > 来自 Cron 作业的 PHP 不运行简单的 Javascript 代码 :(

问题描述

我正在运行一个 API 来检索信息。我必须通过 php 调用这个 API 5 次,但每次我必须等待 60 秒。所以 PHP 文件运行了大约 6 分钟并超时。我尝试延长时间限制,但这不起作用,所以我想到了另一种解决方案。

由于无论如何我都必须在 CRON 作业上运行这个 PHP,所以这里是设置:

-- A.php is run every 10 minutes scheduled in Cron manager. This now runs the header("B.PHP?round=1") command and loads B.PHP

----   B.PHP runs, does what it needs to, now uses javascript setInterval waits 60 seconds and loads (window.location.href ="B.PHP?round=2" again with new parameter (to run 2nd or 3rd etc api token).

问题是,它永远不会在第二轮再次加载 B.PHP。我尝试做 ajax 查询 xmlhttp 所有类型的 JS 脚本来加载页面.....没什么!它似乎要么完全忽略 javascript,要么只是忽略应用加载 b.php 的新参数的 JS 代码


我真的不想使用 sleep(60) 方法(无论如何它都会超时)。我必须使用 Cron 作业,我知道 javascript 是让脚本在等待期间冷却而不导致超时的唯一方法。有什么解决方案吗?拜托伙计们..温柔一点,我是这方面的新手,对linux/ubunto一无所知:(

ps:我有整个网址的B.php还是不行。我必须从 cron 管理器调用 PHP 文件。

我知道 javascript 仅在客户端,但是,JS 代码是...在服务器上加载文件..?呃......我不知道该怎么办:/

标签: javascriptphpcron

解决方案


正如您所说的那样,JavaScript 只是客户端。

此外,cron 作业通常只请求给定的 URL,但不对该结果执行任何操作。他们显然不执行javascript。

您需要将整个逻辑放入您的 PHP 代码中并使用 cronjobs 来“触发”您的脚本。

  • Cronjob 1:每 10 分钟运行一次:start.php
  • Cronjob 2:每 60 秒运行一次(如果您的 API 的限制正好是 60 秒,可能会多一点):process.php

由于您只使用 PHP,因此您需要将变量存储在服务器上的某个位置。这可以是数据库或文件系统上的文件。您可以在此处找到有关如何持久化变量的更详细说明: PHP 在服务器上存储单个变量?. (在我的示例中,我使用文件作为存储)

处理.php:

// number of times the script should be executed
$maxRounds = 5;

// load $round from your storage
$round = file_get_contents('store.txt');

if ($round < $maxRounds) {
    // increase round number for the next call
    // you may want to add some checks to determine if the current round was successful before increasing the value
    // depending on how log your round takes, it might be wise to add another variable (eg "working") to the store, so that multiple calls to the process file do not overlap
    file_put_contents('store.txt', $round + 1);

    // execute your code using the $round argument
    doRound($round);
}

else {
    // already done all rounds
}

开始.php

// reset the $round variable
file_put_contents('store.txt', 0);

请记住,此代码尚未准备好生产,但它应该为您指明正确的方向:)


推荐阅读