Allow Task to be Run only Single Time


Hi CakePHP,
I have a console task that runs in the background, however it does a lot of database cleaning, and I want to make sure it’s executed only once.

I tried locking the file with flock as described in:

however this causing problems with the system.

So is there a way within CakePHP 2.9.1 to lock a task or detect it’s running already and abort, or do I need to write the PID to a file and check manually?

Many thanks.


I suggest you write the current timestamp to a file like task.lock and delete the file when the task is done. At the beginning of your task, you can check if the file exist and decide to exit the task if it’s there.

The reason I would put the timestamp in the lock file is because this gives you the option to not only check if the file is there but also to see how long the task is been going and maybe halt it when it’s taking to long.