SecurityGate
SecurityGate

Reputation: 101

Loop function in Ruby to write multiple times

I've been tasked with creating a server monitor that tests the system at standard intervals, and if it's beyond a certain level, the program will send an email to the user. Along with sending an email, it will also create a file that will show the load averages every 60 seconds. I can't seem to get the loop to write to a new line every time, it just keeps over-writing the first line, over and over. What am I missing?

require 'fileutils'

def LoadAvg()
  return `cat /proc/loadavg | awk '{print $1" "$2" "$3}'`
end

def Timer()
  servername = `uname -n`.strip
  t = Time.now
  taber = t.strftime("%m-%d-%Y-%T")
  filename = "#{servername}_Systemcheck_#{taber}.txt"
  FileUtils.touch(filename)

while(true)
  File.open(filename, 'w') { |x|
    x.puts "#{t.strftime("%I:%M:%S %p")} - #{LoadAvg()}"
    puts LoadAvg()
    sleep(60)
  }
 end
end

Timer()

Upvotes: 1

Views: 146

Answers (1)

phoet
phoet

Reputation: 18835

if you want to APPEND to the file use a instead of w.

unrelated: use Monit, God or Bluepill!

Upvotes: 2

Related Questions