If I'm understanding you correctly then methinks you might want to "man at" (sudo apt-get install at). Set up your cronjob normally but use 'at' to trigger it on sunset.
Start with a wrapper script which defines the environment. 'at', like 'cron' uses a restricted environment so let's make it a bit more like the command line. I've assumed your scripts are going to be in $HOME/bin - doesn't matter, adjust PATH below to taste.
Code: Select all
foo@pi18:~/bin $ cat run.sh
#!/bin/bash
PATH="$HOME/bin:/usr/bin:/sbin:/bin"
export PATH
#redirect output (debug - no mail)
"$@" >/tmp/z 2>&1
#normal (use 'mail' command)
#"$@"
..'chmod u+x run.sh' above. You can use the above in a crontab as well.
Here's your actual script. It's got its environment from "run.sh" and I envisage you'll have collisions once in a while when the (unchanging) cronjob collides with "sunset" so here's a crude lockfile mechanism..
Code: Select all
foo@pi18:~/bin $ cat myjob
#!/bin/bash
NAM=$(basename "$0")
LCK="/tmp/$NAM.lck"
[ -f "$LCK" ] && {
echo "$NAM: Skipped - already running!" 1>&2
exit 1
}
touch "$LCK"
#sleep 90
echo "Your script here"
rm -f "$LCK"
..'chmod u+x myjob' above. There's actually a better way to handle the lockfile - just about any way is better than the above but I'm keeping it bare bones. There's a shellscript thing called a "trap" which can help but forget that for now. Let's just get something to happen..
Code: Select all
foo@pi18:~/bin $ EDITOR="nano -w" crontab -e
*/1 * * * * /home/foo/bin/run.sh myjob
..set to once per minute for testing purposes. They key part is setting up the 'at' job. You do it thusly..
Code: Select all
foo@pi18:~/bin $ echo "$HOME/bin/run.sh myjob" | at "now+1 min"
Summary: once you've got the above working all you have to do is have whatever figures out sunset, issue..
Code: Select all
echo "$HOME/bin/run.sh myjob" | at "22:26 2020-03-11"
..with the correct sunset time and adjust "run.sh" so it sends mail again.
The two 'mail' commands you need to know are "n" (next mail) and "q" (exit). Oh and for 'at'..
Code: Select all
foo@pi18:~/bin $ atq
19 Thu Mar 12 00:00:00 2020 a foo
foo@pi18:~/bin $ at -c 19
(output snipped)
foo@pi18:~/bin $ atrm 19
foo@pi18:~/bin $ atq
Simples! (sez the man who hasn't had to use 'at' in years and had to look most stuff up again)
