Search code examples
phpcronflock

Run PHP Script via cronjob and avoid duplicate PHP process (flock)


I have been reading about how to run a cronjob and avoid a duplicate execution of the cronjob. Meaning, if the cronjob is already running, don't run another instance of it. If the cronjob is not running, start running the process again, based on the cronjob schedule.

flock() is the solution to do so, and as stated here: https://stackoverflow.com/a/33416116 the way to set up a cronjob with flock is as follows:

* * * * * flock -n /tmp/script.lockfile /usr/local/bin/script

However, when I am trying to set up my PHP script in the cronjob with the use of flock, it is not working. I set it up as follows:

*/10 * * * * flock -n /tmp/my-script.lockfile cd /var/www/html/wp-content/plugins/my-plugin/; php my-script.php

I tried to test it in the console directly, without the use of cronjob, and while it creates the my-script.lockfile file, it does not run the my-script.php script. The error says:

flock: failed to execute cd: No such file or directory Could not open input file: my-script.php

Is there something I am missing here? Does flock() only works with .sh scripts? And if so, how can I adapt my PHP script to work with flock()?


Solution

  • Looks like if you want to use more complex command you have to prefix it with -c and wrap in ".

    */10 * * * * flock -n /tmp/my-script.lockfile -c "cd /var/www/html/wp-content/plugins/my-plugin/; php my-script.php"