www www - 10 days ago 4
Linux Question

How to ensure a rake task only running a process at a time

I use crontab to invoke rake task at some time for example: every 3 hour

I want to ensure that when crontab ready to execute the rake task
it can check the rake task is running. if it is so don't execute.

how to do this. thanks.

Answer

You could use a lock file for this. When the task runs, try to grab the lock and run the rake task if you get the lock. If you don't get the lock, then don't run rake; you might want to log an error or warning somewhere too or you can end up with your rake task not doing anything for weeks or months before you know about it. When rake exits, unlock the lock file.

Something like RAA might help but I haven't used it so maybe not.

You could also use a PID file. You'd have a file somewhere that holds the rake processes process ID. Before starting rake, you read the PID from that file and see if the process is running; if it isn't then start up rake and write its PID to the PID file. When rake exists, delete the PID file. You'd want to combine this with locking on the PID file if you want to be really strict but this depends on your particular situation.