Ruby: Detect times when Fedora machine is powered-on

216 views Asked by At

feels like I visited stackoverflow 100 times before. Always found good solutions, but now I'm stuck.

I want to monitor how long a computer runs every day. This is part of a program written in Ruby, running on a Fedora machine.

Previously I did similar things under Windows, where it is possible to catch the related power events using WndProc. However, with Fedora (or Linux in general) I don't find a good hook to detect power-on and power-off/suspend/hibernate/....

Any suggestion is highly appreciated.

Thanks, jayrock

EDIT: Seems I haven't been clear in what I want to achieve. Actually want to have information about not only the current uptime but also past uptimes. Thus I should know "the computer has been running for x hours over the last 14 days" or similar.

Another addition is that e.g. the last command doesn't do the job either - it doesn't show if the system goes to hibernate or suspend.

3

There are 3 answers

0
Shaun Hare On

I don't know the ruby specifics but there is a command uptime in linux.

I think in ruby you need to use System

so it would be something like system 'uptime'

Then you can parse the results of that

0
maletor On

You would use backticks like uptime StackOverflow regards them as code styles though in this answer box.

5
Fred Foo On

You may want to parse the output from the last command, which logs users' logins. If the pseudo-user reboot "logged in", you know the system was rebooted. (This is valid for Ubuntu; maybe Fedora uses a different name, such as boot.)

There may be a more direct interface; Google around for ruby + utmp. The utmp file, commonly in /var/run, records the data that the last command reports.