Tuesday, May 1, 2012

How to turn my PC off at night?

Hey guys,
A month ago my brother asked me to recommend him a software for automatically shutdown the PC,
I refered him a software called Task Scheduler (for Windows 7), which has a message notifier before  shut down.
I decided to search for a similliar tool for my linux box, but couldn't find any tool with a msgbox notifier.
So eventually I decided to write one in bash, I added an entry to the crontab table, which will execute the script each night at 02:00 AM.
In case I'm working on the PC at night, there is a option to postpone the shutdown to a later hour.
I used Zenity for adding a nice touch of GUI, so it would be more user friendly.
A dialog box pops up on the screen and shows via progress bar how much time is left before shutdown, here is a screen shot:



Here is the script:

#!/bin/bash
if [ -z "$1" ]; then
    echo "Error: Please enter the duration in minutes..."
    exit
fi

scriptPath=`pwd`
# converting minutes into seconds
duration=$(($1*60));      
timeToShutDown=$((`date +%s` + $duration))
steps=100;
userName=`whoami`

counter=1;

while [  $(($counter<= 100 )) ]    
 do
  echo $counter
 timeLeft=$(($timeToShutDown-`date +%s`))
 echo "#Hi $userName, the PC would get turned off in $timeLeft Seconds"
 sleep  `echo "scale=2; $duration/$steps" | bc`
 counter=$((counter+1));
 done | zenity --display=:0.0 --width 600 --progress --title="Turning off PC at "`date +"%H:%M:%S[Seconds]"` 
 --text="Turning off PC at ..." --auto-close

#        Value 0  The have passed so shutting down engines
#   Value 1  User pressed Either cancel or the exit X, so we should postpone the shutdown
if [ "$?" = 1 ];
then
   echo "Schedualing a task in 2 minutes..."
   echo "$scriptPath/shutDownByOrder 20" | at now + 120 minutes
else
 echo "Shutting down!!!"
 sudo shutdown -h +1 "turning off your PC in 1 minute!!"
fi


Try it on your linux box and Enjoy! ;-)

No comments:

Post a Comment

About