Last active
January 15, 2023 00:00
-
-
Save kepsic/b041f4ac8b3ff42f12dc0fa2869ded83 to your computer and use it in GitHub Desktop.
Python schedule extension to run task on sunset or sunrise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# This is attempt to mix together python astro and schedule. | |
# Author: Andres Kepler <andres@kepler.ee> | |
import datetime | |
from astral import LocationInfo | |
from astral.sun import sun | |
from schedule import Scheduler as _Scheduler | |
from schedule import Job as _Job | |
def job(message="Task"): | |
print("I'm working on:", message) | |
class Job(_Job): | |
city = LocationInfo("London", "England", "Europe/London", 51.5, -0.116) | |
last_sunrise = None | |
last_sunset = None | |
def __init__(self, interval, scheduler): | |
super().__init__(interval, scheduler) | |
def at_sunrise(self): | |
s = sun(self.city.observer, date=self.next_run) | |
self.last_sunrise = s["sunrise"] | |
return self.at(self.last_sunrise.strftime("%H:%M:%S")) | |
def at_sunset(self): | |
s = sun(self.city.observer, date=self.next_run) | |
self.last_sunset = s["sunset"] | |
return self.at(self.last_sunset.strftime("%H:%M:%S")) | |
def rescedule_astro(self): | |
if self.last_sunset: | |
self.at_sunset() | |
if self.last_sunrise: | |
self.at_sunrise() | |
def _schedule_next_run(self): | |
super()._schedule_next_run() | |
self.rescedule_astro() | |
class Scheduler(_Scheduler): | |
def __init__(self): | |
super().__init__() | |
def every(self, interval=1): | |
""" | |
Schedule a new periodic job. | |
:param interval: A quantity of a certain time unit | |
:return: An unconfigured :class:`Job <Job>` | |
""" | |
job = Job(interval, self) | |
return job | |
schedule = Scheduler() | |
schedule.every().friday.at_sunrise().do(job, message="Friday Sunrise") | |
schedule.every().day.at_sunset().do(job, message="Everyday Sunset") | |
print(schedule.jobs) | |
print(schedule.run_all()) | |
print(schedule.jobs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment