Scalable, Delayed PHP Processing

后端 未结 15 923
长情又很酷
长情又很酷 2020-12-08 01:41

I\'m working on an online PHP application that has a need for delayed PHP event. Basically I need to be able to execute arbitrary PHP code x many seconds (but it could be da

15条回答
  •  太阳男子
    2020-12-08 01:54

    This seems like the perfect place for an event Queue in a database.

    Have your user-created events (triggered by visiting the web page) create an entry into the DB that includes the instructions for the action to take place, and the timestamp for when it should happen. You Daemon (either a persistant application or triggered by CRON) checks the DB for events that should have happened ( $TriggerTime <= time()) and that have not been flagged as "processed" yet. If you find one or more of these events, execute the instruction, and finally mark the event as "processed" in the DB or simply delete the entry.

    The bonus of using the DB to store the events (and not something that is resident in the RAM of an application) is that you can recover from a crash without data loss, you can have more than one worker reading in a single event at a time, and you can modify the event's simply.

    Also, there are lots of folks who use PHP as a general daemon scripting language on servers, etc. Cron can execute a PHP script (and confirm that an instance of that "app" is already running) that checks the Event Queue every-so-often. You can have a little app that dies after a minute of inactivity, and then gets restarted by CRON. The app can check the DB for entries at a fast frequency of your choosing (like 1s). Normally Cron cannot do a timing event faster than once per minute.

提交回复
热议问题