Starting / Stopping php script running in background from browser

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

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.

回答1:

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).



回答2:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!