Android and Linux

Sunday, February 20, 2011

Dawn/Dusk scheduler for Linux

I wanted to run some different commands in the morning and at night in order to set some variables to be used in home automation and switch my new camera from night mode to daytime mode, so I made a little scheduler to run things at dawn and dusk. There are probably other ways to do this, but this is the first time I've tried and I figured out this simple solution and think I'll stick with it.

First, create two files named "dawn" and "dusk" and put any commands you want to run in those scripts. They can be blank for now, but go ahead and make them because our scheduler will be looking for them.

Secondly, we need it to get the sunrise/sunset times. I'll have to leave this one to the reader. There are various services that will calculate the precise times for your latitude/longitude, but in my case I just grabbed it from my local TV news station's weather page. Lucky for me, dumping the page with a console browser gives me the sunrise/sunset times for the entire week and grabbing the top two with this command:
lynx -dump [site] | egrep -i -m 2 "sunset|sunrise" > suntimes
results in this output being put in the file named suntimes:

Sunrise: 07:18
Sunset: 18:22

So, again, this part will depend on your source, but what you want to get is two lines containing the sunrise and sunset time.

Once you figure out the command to get the sunrise/sunset times, put it on the first line of a new script and add these two lines below it:
at $(grep -i sunset suntimes | awk '{ print $2 }') < dawn
at $(grep -i sunrise suntimes | awk '{ print $2 }') < dusk
What that does is tell the at command to run the commands in the day or night file at the time in the second column of line containing "sunrise" or "sunset." The output from the first command is "at 07:18 < dawn" which tells the at scheduler to go run every command in the dawn file at 07:18. The second command is "at 18:22 run the dusk file"

So, running this daily with cron will automatically update the sunrise and sunset times and tell the system to run the dawn/dusk files according to the sunrise/sunset times. You can just add commands to the dawn/dusk files at any time.

That's the idea anyway. This is just an example, you'll probably want to use the full path for the suntimes, dawn and dusk files.

Followers