Limit instances of rake task
Is there a way to limit the number of instances of a rake task?
I have a rake task for reading emails that runs every 5 mins as a cron job.
Sometimes the rak开发者_JS百科e tasks takes more than 5 mins to complete and another rake task is launched before it finishes.
There are hacky workarounds to check ps -Af
inside the rake file but I
am looking for cleaner way to limit launching multiple instances of the
rake tasks similar to how the daemon gem does.
Checking emails is just an example, I have several such rake tasks that involve polling multiple servers.
You could also just use a PidFile.
First, install the 'pidfile' gem. Then make your task like this:
task :my_task => :environment do |task|
PidFile.new(:piddir => Rails.root.join('tmp', 'pids'), :pidfile => task.name)
# do some stuff
end
Still can't find a super elegant way, so I resorted to saving a unique file for each rake task.
This is how the rake task looks now -
run_unique_rake(__FILE__) do puts "\n is running\n" sleep(40) end
here is run_unique_rake
def self.run_unique_rake(file) path = RAILS_ROOT + "/" + CONFIG['rake_log'] + "/" + File.basename(file) unless File.exists?(path) `touch #{path}` yield if block_given? `rm #{path}` end end
Still hoping for an elegant way within rake to limit to a single instance.
精彩评论