启动/停止从浏览器在后台运行的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.

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

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.