Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

275
Views
Getting system uptime in ruby

I am looking for a better way to retrieve a systems uptime. My current method works, but I feel like things can be done better.

def uptime_range
  days_up = `uptime | awk {'print$3'}`.chomp.to_i
  hours_up = `uptime | awk {'print$5'}`.delete(',').chomp
  seconds_up = time_to_seconds(days_up,hours_up)
  started = Time.now - seconds_up
  "#{started.strftime('%Y.%m.%d.%H.%M')}-#{Time.now.strftime('%Y.%m.%d.%H.%M')}"
end
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

On linux systems you can open /proc/uptime and read seconds since the machine booted.

def started
   Time.now - IO.read('/proc/uptime').split[0].to_f
end 

Edit: changed to_i to to_f. With to_i, the value of started when displayed as a string or integer is more likely to vary, especially if the boot time was close to the middle of a second rather than at the beginning or end of a second.

over 4 years ago · Santiago Trujillo Report

0

You could check the sysinfo gem. It should give system-independent access to the uptime data.

over 4 years ago · Santiago Trujillo Report

0

A rubygem called linux_stat can do that pretty well:

require 'linux_stat'

LinuxStat::OS.uptime
=> {:hour=>40, :minute=>46, :second=>19.75}

Code copied from here.

But if you don't feel like using another gem for this trivial task, you can do this:

uptime = IO.read('/proc/uptime').to_f
uptime_i = uptime.to_i

puts({
    hour: uptime_i / 3600,
    minute: uptime_i % 3600 / 60,
    second: uptime.%(3600).%(60).round(2)
})

Which prints:

{:hour=>0, :minute=>39, :second=>54.89}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!