How to ensure that the rake task only runs the process at a time

I use crontab to call the rake task for some time, for example: every 3 hours

I want to make sure that when crontab is ready to execute the rake command it can verify that the rake task is running. if that is not the case.

how to do it. thanks.

+4
source share
3 answers

You can use a lock file for this. When the task is running, try to capture the lock and run the rake task if you get a lock. If you do not get a lock, then do not use rake; you may need to file an error or warning somewhere too, or you can finish your rake task without doing anything for weeks or months before you find out. When the rake comes out, open the lock file.

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

You can also use the PID file. You will have a file somewhere that contains the rake process process id. Before starting the rake, you read the PID from this file and see if this process works; if he does not start the rake and writes his PID to the PID file. When rake exists, delete the PID file. You want to combine this with locking in a PID file if you want to be very strict, but it depends on your specific situation.

+3
source

I will leave it here because I find it useful:

task :my_task do pid_file = '/tmp/my_task.pid' raise 'pid file exists!' if File.exists? pid_file File.open(pid_file, 'w'){|f| f.puts Process.pid} begin # execute code here ensure File.delete pid_file end end 
+18
source

All you need is a gem called pidfile .

Add this to your gemfile:

 gem 'pidfile', '>= 0.3.0' 

And the task may be:

 desc "my task" task :my_task do |t| PidFile.new(piddir: "/var/lock", pidfile: "#{t.name}.pid") # do something end 
+1
source

All Articles