Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

I'll leave this here because I think it's 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

All you need is a gem named pidfile.

Add this to your Gemfile:

gem 'pidfile', '>= 0.3.0'

And the task could be:

desc "my task"
task :my_task do |t|
  PidFile.new(piddir: "/var/lock", pidfile: "#{t.name}.pid")
  # do something
end
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top