Automating the schedule

Having a working timelapse setup I found that many of the sunrises were obscured by clouds and of course the time of the sunrise changes every day and I didn't want to change the cronjob every few days to capture the sun. Fortunately there are two libraries that can assist with automation of the cronjob.

Getting the time of the next sunrise

First install ephem

pi@pi:~ $ pip3 install ephem

The python code is below, the library can be used for a much wider range of astronomical events including sunset, moonrise and similar events for all the planets.

import ephem

vhv=ephem.Observer()
# location
vhv.lat='51.4176'
vhv.lon='5.4060'
vhv.date = datetime.datetime.now()

sun = ephem.Sun()
# This is the time of the next sunrise
rising=ephem.localtime(vhv.next_rising(sun))

# This is the offset for the filming to start
start_offset=datetime.timedelta(minutes=45)

# This is the time the filming should start
film_start=rising-start_offset

# Get the hour and minute to update the cronjob
cron_hour=film_start.hour
cron_minute=film_start.minute

Updating the cronjob

There are two libraries with similar names, we need python-crontab. Do not install crontab otherwise you'll get syntax errors.

pi@pi:~ $ pip3 install python-crontab

The code below only works if there is a cronjob in place via crontab -e with the comment timelapse as below.

9 5 * * * python3 /home/user/timelapse/timelapse.py # timelapse
from crontab import CronTab

my_cron = CronTab(user='stuart')
for job in my_cron:
    if job.comment == 'timelapse':
        job.hour.on(cron_hour)
        job.minute.on(cron_minute)
        my_cron.write()

Adding the preceeding two blocks to the end of the original timelapse code will update the next days timelapse schedule after todays is completed.

Previous Post Next Post