I made it a little bit more fancy to make things easier.
#!/bin/sh
#
# Prints idle time in seconds
# ... or waits TIME seconds while idle then beeps
# ... or waits TIME seconds while idle then executes COMMAND.
#
# Copyleft Misalf 2017
SLEEP="2" # How long to wait between checks for idle time.
TIME="$1"
shift
COMMAND="$@"
# Requires w from procps .
TCUSER="$(cat /etc/sysconfig/tcuser)"
[ -n "$TCUSER" ] && su -c "tce-load -i procps >/dev/null" - "$TCUSER"
f_print_usage() {
echo "Usage: $(basename $0) [TIME [COMMAND]]"
echo ""
echo "Without arguments just prints idle time in seconds and exits."
echo "If TIME is given, beeps if idle for TIME seconds and exits."
echo "If TIME and COMMAND is given, executes COMMAND if idle for TIME seconds and exits."
}
f_get_idle() {
w -hs | awk '{
if($3 ~ /days/){
split($3,d,"days");
print d[1]*86400
}
else if($3 ~ /:|s/){
if ($3 ~/s/) {sub(/s/,"",$3); split($3,s,"."); print s[1]}
else if ($3 ~/m/) {split($3,m,":"); print (m[1]*60+m[2])*60}
else {split($3,m,":"); print m[1]*60+m[2]}
}
else {print $3}
}'
}
f_get_lowest_idle() {
IDLE=""
for i in $(f_get_idle) ; do
[ -z "$IDLE" ] && IDLE="$i"
[ "$i" -lt "$IDLE" ] && IDLE="$i"
done
}
if [ -n "$TIME" ] ; then
case $TIME in
''|*[!0-9]*)
echo "Cannot wait \"$TIME\" seconds."
echo ""
f_print_usage
exit 1
;;
esac
if [ -n "$COMMAND" ] ; then
#echo "Will run \"$COMMAND\" if idle for \"$TIME\" seconds..."
while true ; do
f_get_lowest_idle
if [ "$IDLE" -ge "$TIME" ] ; then
#echo "\"$IDLE\" seconds reached."
eval "$COMMAND"
break
fi
sleep "$SLEEP"
done
else
#echo "Will beep if idle for \"$TIME\" seconds..."
while true ; do
f_get_lowest_idle
if [ "$IDLE" -ge "$TIME" ] ; then
echo "*BEEP*"
echo -en "\033[10;110]\033[11;100]\007" > /dev/tty0
usleep 110000
echo "*BOOP*"
echo -en "\033[10;55]\033[11;100]\007" > /dev/tty0
break
fi
sleep "$SLEEP"
done
fi
else
f_get_lowest_idle
echo "$IDLE"
fi
You could
idle.sh 10 echo test &
which prints the word "test" after 10 seconds of inactivity.
Or
idle.sh 3600 sudo poweroff &
which shuts down after 1 hour of inactivity.
In such a case where the command is executed after a long idle time,
and it doesn't need to be executed exactly at that second,
it might make sense to increase the value of the SLEEP variable to like 60 or so.
Or
idle.sh 10 &
which makes beep boop after 10 seconds of inactivity (if you have a PC speaker).