开发者

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 vi开发者_运维百科sit. Is there some way to prevent sleep during execution and let Windows sleep after?

Any crazy ideas are welcome ;-)


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)


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!


I don't do much on the Windows platform, but the following approach seems logical:

  1. In your program, use whatever ruby libs are available for the windows platform to check whether auto suspend/sleep is enabled.
  2. If enabled, disable it.
  3. Run your long tasks.
  4. Once done, re-enable auto suspend/sleep

You are probably going to need to add some additional logic to re-enable auto suspend if your program errors out.

Also, the application may need to be run under an account that has access to enable/disable auto suspend.

Hope this helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜