source: misc/power-saver@ 361

Last change on this file since 361 was 361, checked in by Rick van der Zwet, 13 years ago

Initial commit of power-saver script, which helps to keep the electricity bill down.

  • Property svn:executable set to *
File size: 1.8 KB
Line 
1#!/bin/sh
2#
3# Shutdown system if it has been idle for 1 hour and no active users are logged
4# in.
5#
6# Usage: This script is mainly used on a home server used for building FreeBSD
7# World and kernels. As soon it is done it can shutdown if not being used
8# anymore. The system has Wake-On-Lan support and can thus be activated again
9# from remote.
10#
11# Please run from cron every CRON_INTERVAL minutes:
12# */5 * * * * * /usr/local/bin/power-saver
13#
14# Rick van der Zwet <info@rickvanderzwet.nl>
15#
16
17CRON_INTERVAL=5
18MAX_LOAD=0.10
19MAX_IDLE=60
20
21# Stored as <epoch> <load>
22DAT_FILE='/tmp/power-saver.dat'
23
24# Current values
25EPOCH=`date "+%s"`
26LOAD_15=`sysctl vm.loadavg | awk '{print $5}'`
27
28# Empty file needs to be created and filled
29echo "$EPOCH $LOAD_15" >> $DAT_FILE || exit 1
30
31# Check if countdown has already been started
32ps -x | grep -q '[0-9] shutdown' && exit 0
33
34# Check if all users are no longer active
35SHORTEST_IDLE=`w -ih | awk '{print $5}' | head -1`
36# Hack to make sure time is always in minutes
37SHORTEST_IDLE_IN_MIN=`echo $SHORTEST_IDLE | awk -F: '{if (NF > 1){print $1 * 60 + $2}else{print $1}}'`
38if [ -z "$SHORTEST_IDLE_IN_MIN" ]; then
39 # No users are currently logged in
40 continue
41elif [ "$SHORTEST_IDLE_IN_MIN" = "-" ]; then
42 # User is still active an minute ago
43 exit 0
44elif [ $SHORTEST_IDLE_IN_MIN -le $MAX_IDLE ]; then
45 # User is still active less than MAX_IDLE ago
46 exit 0
47fi
48
49# Count the amount entries we are current on our way
50IDLE_COUNTS=`awk -vMAX_LOAD=$MAX_LOAD -vMAX_IDLE=$MAX_IDLE -vEPOCH=$EPOCH \
51 'BEGIN{MIN_TIME=EPOCH-MAX_IDLE;s=0}{if ($1 > MIN_TIME && $2 > MAX_LOAD){s += 1}}END{print s}' $DAT_FILE`
52
53# We are idle for over $MAX_IDLE time, starting shutdown
54if [ $IDLE_COUNTS -gt `expr $MAX_IDLE / $CRON_INTERVAL` ]; then
55 echo shutdown -p "+15" "Cancel: sudo killall -SIGTERM shutdown"
56fi
Note: See TracBrowser for help on using the repository browser.