dousong1926
2014-03-21 10:54
浏览 75
已采纳

启动/停止从浏览器在后台运行的php脚本

I'm pretty new to PHP. This is my first time actually, so I apologize in advance if the question sounds dumb.

I have a php script which fetches data from an external API and updates my database regularly. I know that the best way to do this is to use a cron job. However, I am using an infinite loop which sleeps for a particular time between each update.

Now, I need to allow the user (admin) to start / stop the script and also allow them to change the time interval between each update. The admin does this through a UI. What is the best way to do this? How do I execute the script in the background when the user clicks start and how do I stop the script?

Thanks.

图片转代码服务由CSDN问答提供 功能建议

我是PHP的新手。 这实际上是我的第一次,所以如果问题听起来很愚蠢,我会提前道歉。

我有一个PHP脚本,它从外部API获取数据并定期更新我的数据库。 我知道这样做的最好方法是使用cron作业。 但是,我使用的是一个无限循环,它会在每次更新之间休眠一段时间。

现在,我需要允许用户(admin)启动/停止脚本,并允许他们更改每次更新之间的时间间隔。 管理员通过UI完成此操作。 做这个的最好方式是什么? 当用户单击“开始”时如何在后台执行脚本以及如何停止脚本?

谢谢。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dqmdlo9674 2014-03-21 13:40
    已采纳

    I think the ideal solution would be the following:

    1. Have the background job run as a cronjob every minute (instead of a loop which can cause memory leaks). PHP was not designed to be a daemon.

    2. Set a DB flag in the cronjob for on/off, everytime it runs it checks if its on or off, if off it exists if on it continue.

    3. In the UI you turn that flag on or off depending on what the admin needs.

    I think that is the best way to go (and easiest).

    点赞 打赏 评论
  • doucu5836 2014-03-21 13:33

    You might want to take a look at Threading in PHP -> http://www.php.net/manual/en/class.thread.php

    An other option is to either set a SESSION (which is a little tricky, since you won't catch it in the same call) or you generate a file wich tells the script to stop/exit/fail/what ever if that file exists.

    点赞 打赏 评论

相关推荐 更多相似问题