Skip to content

Instantly share code, notes, and snippets.

@jkominek
Created February 2, 2022 05:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkominek/49e51382873e5478dd85111a2308ad8f to your computer and use it in GitHub Desktop.
Save jkominek/49e51382873e5478dd85111a2308ad8f to your computer and use it in GitHub Desktop.
generate cron jobs based on sunrise/sunset, independent of daylight savings time
#!/usr/bin/env python3
import ephem
from datetime import datetime, timedelta, timezone
# don't generate any invocations until
SKIP_UNTIL = datetime(2021, 10, 16, 12, 0, 0)
# times to run per day
FOODS = 8
# thing to run
SCRIPT = "/home/pi/dispense.py"
sun=ephem.Sun()
# where you are
boulder=ephem.Observer()
boulder.lat='40:0:53.94'
boulder.lon='-105:16:13.96'
boulder.date=datetime.now().replace(hour=0, minute=0, second=0).astimezone(timezone.utc)
print("# {} {}".format(boulder.lat, boulder.lon))
if SKIP_UNTIL > datetime.now():
print("# Skipping until {}".format(SKIP_UNTIL))
print()
def generate(sunrise, sunset):
s = "# {} {} -> {} ({})".format(
sunrise.date().isoformat(),
sunrise.time().isoformat()[:8],
sunset.time().isoformat()[:8],
sunset - sunrise)
print(s)
# start one hour after sunrise
start = sunrise + timedelta(hours=1)
# stop 3/4 of the way between sunset and midnight
midnight = datetime(sunset.year, sunset.month, sunset.day) + timedelta(days=1)
nightoffset = 3.0 * ((midnight - sunset) / 4.0)
stop = sunset + nightoffset
step = (stop - start) / (FOODS - 1)
cronline = "{:2d} {:2d} {:2d} {:2d} {} {} sleep {:2d} ; {}"
for j in range(FOODS):
t = start + j * step
t -= timedelta(seconds=1)
if t <= SKIP_UNTIL:
print("# ", end='')
print(cronline.format(t.minute, t.hour, t.day, t.month, "*", "root",
t.second, SCRIPT))
print()
for i in range(7):
sunrise = boulder.next_rising(sun)
boulder.date = sunrise
sunrise = ephem.localtime(sunrise)
sunset = boulder.next_setting(sun)
boulder.date = sunset
sunset = ephem.localtime(sunset)
generate(sunrise, sunset)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment