Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a Windows 7 PC from going to sleep while a Ruby program executes

I need to run a Ruby app on a customer computer. It will usually take a couple of days to finish (copies big backup files). The problem is if sleep is enabled, it will interrupt the app. If not the computer will stay on for weeks untill my next visit. Is there some way to prevent sleep during execution and let Windows sleep after?

Any crazy ideas are welcome ;-)

like image 914
Dick Colt Avatar asked Nov 08 '10 17:11

Dick Colt


2 Answers

Here is upvoted advice to use SetThreadExecutionState WinAPI function, which enables an application to inform the system that it is in use, thereby preventing the system from entering sleep or turning off the display while the application is running.
Something like:

require 'Win32API'
ES_AWAYMODE_REQUIRED = 0x00000040
ES_CONTINUOUS = 0x80000000
ES_DISPLAY_REQUIRED = 0x00000002
ES_SYSTEM_REQUIRED = 0x00000001
ES_USER_PRESENT = 0x00000004
func = Win32API.new 'kernel32','SetThreadExecutionState','L'

func.call(ES_CONTINUOUS|ES_SYSTEM_REQUIRED)
# doing your stuff...
func.call(ES_CONTINUOUS)


Or just put something on keyboard (you said crazy ideas are welcome)
like image 168
Nakilon Avatar answered Nov 14 '22 22:11

Nakilon


If this is a command-line program, then you can send commands from Ruby to the command line using backticks like this

puts `command here`

so then you can set the computer to not sleep by sending this command

c:\windows\system32\powercfg.exe -change -standby-timeout-ac 0

like this

puts `c:\\windows\\system32\\powercfg.exe -change -standby-timeout-ac 0`

You have to escape the \ with the double. Tested and works for me, although on a laptop. I assume it would function the same on a desktop.

The number at the very end is the time in minutes before putting the computer to sleep. I don't know if you can retrieve the original value, but you can set it to any number. Thus, to put the computer to sleep after 10 minutes, you would send

puts `c:\\windows\\system32\\powercfg.exe -change -standby-timeout-ac 10`

So you can turn off sleep at the beginning of the script and turn the sleep back on afterwards.

Hope this is suitable for you!

like image 22
Paul Hoffer Avatar answered Nov 14 '22 22:11

Paul Hoffer