防止脚本中的睡眠

Mr *_*ooz 15 windows-7 sleep cygwin command-line

有没有办法防止 Windows 在命令行或 cygwin 上运行程序时进入睡眠模式?理想情况下,我希望可以使用以下内容:

nosleep myscript.sh
Run Code Online (Sandbox Code Playgroud)

背景

有时我会启动手动备份或大文件传输等长时间运行的工作,我发现 Windows 经常在这些工作完成之前进入睡眠状态。我希望能够在命令运行时启动命令并阻止睡眠模式,但是一旦命令完成,它就会自动再次工作。

har*_*ymc 15

您可以powercfg在脚本中使用来更改 PC 等待进入睡眠状态的时间:

从不进入待机状态:

powercfg -change -standby-timeout-ac 0
Run Code Online (Sandbox Code Playgroud)

15 分钟后进入待机状态:

powercfg -change -standby-timeout-ac 15
Run Code Online (Sandbox Code Playgroud)


Mr *_*ooz 9

这是我根据 harrymc 的响应编写的 bash 脚本。

#!/usr/bin/bash

# NAME
#   nosleep - prevent sleep and hibernation while running a command
#
# SYNOPSIS
#   nosleep COMMAND [ARG]...

# Make sure the power scheme gets restored, even if Ctrl-C happens
cleanup()
{
  powercfg -setactive $SCHEME_GUID
  powercfg -delete    $TMP_GUID
  return $?
}
trap cleanup SIGINT

# Disable sleep and hibernate timers
export SCHEME_GUID=`powercfg -getactivescheme | gawk '{ print $4 }'`
export TMP_GUID=`powercfg -duplicatescheme $SCHEME_GUID | gawk '{ print $4 }'`
if [[ -z $TMP_GUID ]]; then
    echo "ERROR: could not duplicate the current power scheme"
    exit 254
fi
powercfg -setactive $TMP_GUID
powercfg -changename $TMP_GUID nosleep "temporary scheme for disabling sleep and hibernation"
powercfg -change -standby-timeout-ac 0
powercfg -change -hibernate-timeout-ac 0

# Run the command
"$@"

powercfg -setactive $SCHEME_GUID
powercfg -delete    $TMP_GUID
Run Code Online (Sandbox Code Playgroud)


sch*_*sch 5

nosleepCygwin现在有这样的命令。只需安装nosleep包并运行

nosleep myscript.sh
Run Code Online (Sandbox Code Playgroud)

由 Andrew E. Schulman 于 2011 年撰写。参见https://cygwin.com/ml/cygwin/2011-09/msg00151.html

Launchpad 上的源代码。它使用SetThreadExecutionState()(如已经提到的 Insomnia),不会创建单独的电源方案。

Usage: nosleep [OPTION...] command [args]
Run a command while inhibiting computer sleep or hibernation.

  -a, --awaymode             Force away mode instead of sleep mode
  -d, --display              Keep the display on
  -i, --ifacpower            Following options only apply if AC power is on
  -?, --help                 give this help list
  --usage                give a short usage message
  -V, --version              print program version

Report bugs to the Cygwin mailing list <cygwin@cygwin.com>.
Run Code Online (Sandbox Code Playgroud)

请注意,它可以防止系统在空闲时自动进入睡眠状态,而不是系统在用户请求时(例如关闭笔记本电脑盖时)进入睡眠状态。