How to detect whether a PHP script is already running?

后端 未结 9 1336
借酒劲吻你
借酒劲吻你 2021-01-31 11:26

I have a cron script that executes a PHP script every 10 minutes. The script checks a queue and processes the data in the queue. Sometimes the queue has enough data to last ov

9条回答
  •  后悔当初
    2021-01-31 11:29

    You can just use a lock file. PHP's flock() function provides a simple wrapper for Unix's flock function, which provides advisory locks on files.

    If you don't explicitly release them, the OS will automatically release these locks for you when the process holding them terminates, even if it terminates abnormally.

    You can also follow the loose Unix convention of making your lock file a 'PID file' - that is, upon obtaining a lock on the file, have your script write its PID to it. Even if you never read this from within your script, it will be convenient for you if your script ever hangs or goes crazy and you want to find its PID in order to manually kill it.

    Here's a copy/paste-ready implementation:

    #!/usr/bin/php
    

    Just set the path of your lock file to wherever you like and you're set.

提交回复
热议问题