Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 785
www Avatar asked Oct 21 '10 02:10

www


People also ask

How do I run a specific rake task?

Go to Websites & Domains and click Ruby. After gems installation you can try to run a Rake task by clicking Run rake task. In the opened dialog, you can provide some parameters and click OK - this will be equivalent to running the rake utility with the specified parameters in the command line.

How do I run a rake file?

How to run rake? To run a rake task, just call the rake command with the name of your task. Don't forget to include your namespaces when you have them.

What is rake task in rails?

Rake is a popular task runner for Ruby and Rails applications. For example, Rails provides the predefined Rake tasks for creating databases, running migrations, and performing tests. You can also create custom tasks to automate specific actions - run code analysis tools, backup databases, and so on.


3 Answers

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
like image 195
pguardiario Avatar answered Oct 13 '22 00:10

pguardiario


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.

like image 31
mu is too short Avatar answered Oct 12 '22 23:10

mu is too short


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
like image 43
fanjieqi Avatar answered Oct 12 '22 23:10

fanjieqi