每5分钟运行一次PHP脚本

每5分钟运行一次PHP脚本

本文介绍了每5分钟运行一次PHP脚本,避免竞争条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个php脚本,需要运行一次每5分钟。目前我使用cron作业运行它(它的工作原理),但我的主机只允许最少15分钟的时间。

I have a php script that needs to run once every 5 minutes. Currently I'm using a cron job to run it (and it works great) but my host only allows a minimum time of 15 minutes.

所以我的问题是,可以我使用访问者每5分钟触发一个php脚本的运行。我可以很容易地记录它的最后一次跑步,并根据经过的时间重新运行它。

So my question is, can I use visitors to trigger the running of a php script every 5 minutes. I can easily just record the last time it ran, and re-run it based on elapsed time.

但是,我担心比赛条件。重要的是,该脚本只会每隔5分钟一次运行一次。

However, I'm worried about race conditions. It is important that the script only gets run once every 5 minutes.

我的脚本运行大约需要60秒。在这段时间它写入几个文件。如果脚本运行多次,它将损坏文件。此外,如果我没有10分钟没有vistor,那么当下一个vistor到达时运行一次。

My script takes about 60 seconds to run. It writes to a couple files during this time. If the script ran more than once it would corrupt files. Also, if I get no vistors for 10 minutes, then running once when the next vistor arrives is fine.

有一些标准的方法来完成这个任务吗?

Is there some standard way to accomplish this task?

谢谢!

推荐答案

您是否考虑过让脚本运行无限循环

Have you considered just having your script run an infinite loop with a sleep to wait 5 minutes between iterations?

for (;;)
{
  perform_actions();
  sleep(300);
}

或者,您可以有一个文件(例如is_running)在您的脚本开始时的独家,该脚本在结束。

Alternatively, you could have a file (for example, is_running), and get an exclusive lock on it at the start of your script which is released at the end. At least this way you will not do anything destructive.

您也可以合并这两个解决方案。

You could also combine these two solutions.

$fp = fopen("is_running", "r+");

/* is it already running? */
if (! flock($fp, LOCK_EX | LOCK_NB)) return;

for (;;)
{
  perform_actions();
  sleep(300);
}

然后让cron作业每15分钟运行一次。如果进程仍在运行,则只会释放,否则将每5分钟重新启动并恢复更新。

And then have the cron job still run every 15 minutes. If the process is still running, it will just bail out, otherwise it will relaunch and resume updating every 5 minutes.

这篇关于每5分钟运行一次PHP脚本,避免竞争条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 20:23