How to ensure a rake task only running a process at a time
Asked Answered
A

3

5

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.

Assess answered 21/10, 2010 at 2:34 Comment(0)
C
3

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.

Cytaster answered 21/10, 2010 at 5:5 Comment(1)
flock you can try :]Gyimah
S
19

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
Slav answered 3/2, 2012 at 16:43 Comment(0)
C
3

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.

Cytaster answered 21/10, 2010 at 5:5 Comment(1)
flock you can try :]Gyimah
E
1

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
Economical answered 1/12, 2016 at 8:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.