How to run scripts on screen sleep / wake

I'm wondering how to run a script when the screen times out and when it wakes. I am not talking about hibernate or suspend, but only when the screen turns off.

The reason is I have a LED keyboard and want to toggle the built-in LEDs on wake.


Solution 1:

you can use xset -q to check the status of your monitor. so far i have seen DPMS states for the monitor to be "Monitor is On", "Monitor is Off" or "Monitor is in Suspend". you could write a script which you then autostart after xorg starts:

#!/bin/bash
while true; do
    xset -q | grep "Monitor is On"
    if [ $? -eq 1 ]; then
        if [ "`cat /tmp/displaystate`" != "off" ]; then 
            echo "off" > /tmp/displaystate
            # do something when display is switched off
            /opt/myScreenOffAction.sh
        fi
        sleep 1
    else 
        if [ "`cat /tmp/displaystate`" != "on" ]; then 
            echo "on" > /tmp/displaystate
            #do something when display is switched on
            /opt/myScreenOffAction.sh
        fi
        sleep 10
    fi
done

to test your script you can use xset dpms force suspend to put your screen into suspend.

I suggest you grep for "Monitor is On" as it seems there are different states for off as mentioned above.