I don't know of a way to do this without polling some sort of system stats, like the other answers use a screensaver or bash idle timer, or running from .bash_logout, but here's an idea to check CPU usage.
This would still involve polling every n seconds, and if your CPU usage is under whatever amount you choose then you can script whatever you want to run. However, whatever you run could raise the CPU usage, but you could use nice on your "stuff" to not count it.
Here's a test script using top, but you could use mpstat instead, or check load averages instead?
while true
do
idle=$(top -bn2 | grep "Cpu(s)"|tail -n 1|sed "s/.*, *\([0-9.]*\)%* id.*/\1/")
echo "idle is $idle"
if [[ $idle > 90 ]]
then
echo "idle above 90%"
echo "Do stuff now"
else
echo "idle below 90%"
echo "Stop doing stuff now"
fi
sleep 1
done
That's just a script I threw together to test out reading the idle from top. You could parse /proc/stat
but I think it only shows total times, and you'd need to compare results over an interval. Top has it's own problem for me (linux mint 16), on the first run it seems to never change cpustats, as if it has to wait to parse /proc/stat itself, hence the top -bn2
but in theory top -bn1
should work.