prevent sleep in scripts

You may use powercfg in a script to change the time the PC waits until it goes to sleep:

Never go to standby:

powercfg -change -standby-timeout-ac 0

Go to standby in 15 minutes:

powercfg -change -standby-timeout-ac 15

Here's a bash script that I whipped up based on harrymc's response.

#!/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

There is now such a nosleep command in Cygwin. Just install the nosleep package and run as

nosleep myscript.sh

Written by Andrew E. Schulman in 2011. See https://cygwin.com/ml/cygwin/2011-09/msg00151.html

The source on Launchpad. It uses SetThreadExecutionState() (like Insomnia already mentioned), doesn't create a separate power scheme.

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 <[email protected]>.

Note that it prevents the system from automatically going to sleep on idle, not the system from going to sleep if requested by a user (like when closing a laptop lid).