Skip to content

Instantly share code, notes, and snippets.

@caruccio
Last active July 10, 2024 10:44
Show Gist options
  • Save caruccio/f7f3822578f2929a1a8104e116f64f7a to your computer and use it in GitHub Desktop.
Save caruccio/f7f3822578f2929a1a8104e116f64f7a to your computer and use it in GitHub Desktop.
Pause processes during night
#!/bin/bash
#
# This script will stop a list of running proccesses (var PROCS), disable all monitors and CPUs (except cpu-0).
#
# Usage:
# pause [on|off|duration]
#
# With no parameters it will pause right alway.
# If [duration] is specified, it will detect for inactivity and pause, in an infinite loop. Use CTRL+C to exit.
# [duration] accepts the same as the command sleep.
#
PROCS="slack chrome brave firefox" ## Insert here your energy-consuming programs
LAST_CPU=$(lscpu -e=cpu|sed -ne '$s/ //gp')
COLOR_GREEN="$(tput setaf 2)"
COLOR_YELLOW="$(tput setaf 3)"
COLOR_RESET="$(tput sgr0)"
COLOR_BOLD="$(tput bold)"
function sig_proc()
{
local sig=${1:-CONT}
if [ "$sig" == STOP ]; then
echo -e "${COLOR_GREEN}Pausing processes: $PROCS"
else
echo -e "${COLOR_YELLOW}Resuming processes: $PROCS"
fi
printf "%s\n" $PROCS | xargs -l pkill "-$sig" || true
echo -ne $COLOR_RESET
}
function set_cpu_state()
{
local state=${1:-1}
if [ "$state" -eq 0 ]; then
echo -e "${COLOR_GREEN}Disabling CPUs [1..$LAST_CPU]"
else
echo -e "${COLOR_YELLOW}Enabling CPUs [1..$LAST_CPU]"
fi
echo $state | eval sudo tee "/sys/devices/system/cpu/cpu{1..$LAST_CPU}/online" >/dev/null
echo -ne $COLOR_RESET
}
function monitor()
{
xset -display $DISPLAY dpms force ${1:-on}
}
function pause()
{
sig_proc STOP
set_cpu_state 0
monitor off
}
function resume()
{
monitor on
set_cpu_state 1
sig_proc CONT
}
function wait_inactivity()
{
eval $(xdotool getmouselocation --shell --prefix=PREV_)
echo -e "${COLOR_BOLD}$(date): Waiting inactivity for $1 $COLOR_RESET"
while true; do
has_activity=false
sleep $1
eval $(xdotool getmouselocation --shell --prefix CURR_)
#echo Current: $CURR_X, Last: $PREV_X
if [ $CURR_X -eq $PREV_X ]; then
return
fi
PREV_X=$CURR_X
done
}
function wait_activity()
{
echo -e "${COLOR_BOLD}Move mouse or press [ENTER] to resume...$COLOR_RESET"
eval $(xdotool getmouselocation --shell --prefix=PREV_)
while true; do
eval $(xdotool getmouselocation --shell --prefix CURR_)
#echo Current: $CURR_X, Last: $PREV_X
if [ $CURR_X -ne $PREV_X ]; then
return
fi
PREV_X=$CURR_X
if read -t 1 -n 1; then
return
fi
done
}
if [ "$1" == on ] || [ "$1" == pause ]; then
pause
read -p 'Press [ENTER] to resume...'
resume
elif [ "$1" == off ] || [ "$1" == resume ]; then
resume
elif which xdotool &>/dev/null; then
TIMEOUT=${1:-1h}
while true; do
wait_inactivity $TIMEOUT
echo -e "${COLOR_BOLD}${COLOR_GREEN}System is inactive... sleeping$COLOR_RESET"
pause
wait_activity
echo -e "${COLOR_BOLD}${COLOR_YELLOW}System is active... waking up$COLOR_RESET"
resume
done
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment