Skip to content

Instantly share code, notes, and snippets.

@themactep
Last active June 13, 2024 08:59
Show Gist options
  • Save themactep/06f951da3fc05693871cc15aa243dff5 to your computer and use it in GitHub Desktop.
Save themactep/06f951da3fc05693871cc15aa243dff5 to your computer and use it in GitHub Desktop.
Generate cron job lines from sunrise and sunset time provided by api.sunrise-sunset.org
#!/bin/sh
# Set cron jobs by actual sunset and sunrise time
# 2023 Paul Philippov <[email protected]>
# 2023-12-23 - initial script
# 2023-04-28 - use daynight script to switch day mode
# 2024-06-12 - add timezone support
# Please tip the API provider: https://www.buymeacoffee.com/sunrisesunsetapi
# Geographic coordinates of your place
lat="42.17509000"
lng="-82.8248300"
# Timezone (from Thingino environment)
tz="$(fw_printenv -n timezone)"
crontab_file=/etc/crontabs/root
at_sunrise_marker="# at sunrise (autogenerated)"
at_sunset_marker="# at sunset (autogenerated)"
# form request URL
url="https://api.sunrise-sunset.org/json?lat=${lat}&lng=${lng}&formatted=0&tzid=${tz}"
# retrieve and parse sunset and sunrise time
json=$(curl --silent --url "$url")
srh=$(jsonfilter -s "$json" -e @.results.sunrise | awk -F[T:] '{print $2}' | sed 's/^0//')
srm=$(jsonfilter -s "$json" -e @.results.sunrise | awk -F[T:] '{print $3}' | sed 's/^0//')
ssh=$(jsonfilter -s "$json" -e @.results.sunset | awk -F[T:] '{print $2}' | sed 's/^0//')
ssm=$(jsonfilter -s "$json" -e @.results.sunset | awk -F[T:] '{print $3}' | sed 's/^0//')
# create a copy of crontab in ram
tmp_crontab_file=$(mktemp)
cp $crontab_file $tmp_crontab_file
# delete old jobs
sed -i "/$at_sunrise_marker/,+1d" $tmp_crontab_file
sed -i "/$at_sunset_marker/,+1d" $tmp_crontab_file
# create new marked jobs
{
echo "$at_sunset_marker"
printf "%02d %02d * * * daynight night\n" $ssm $ssh
echo "$at_sunrise_marker"
printf "%02d %02d * * * daynight day\n" $srm $srh
} >> $tmp_crontab_file
# replace actual crontab file with the updated one
cp $tmp_crontab_file $crontab_file
exit 0
@johndoewashere2
Copy link

Thanks for the script @themactep
Looks like the data pulled from the API will be for UTC if time zone is not specified.

Adding the following variable:

# Specify time zone as per https://www.php.net/manual/en/timezones.php
tzid="Australia/Melbourne"

And appending tzid string into the json variable will return local sunset and sunrise times:

json=$(curl --silent --url "https://api.sunrise-sunset.org/json?lat=${lat}&lng=${lng}&formatted=0&tzid=$tzid")

@themactep
Copy link
Author

Thank you, @johndoewashere2. I have changed the script adding support for timezone value from Thingino environment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment