We can use the Python sched
module and exec()
the script. Thus given Sample.py
:
print ("Hello World")
... we can write another script sched_sample.py
:
import sched, time
dayLen = 86400 # seconds
weekLen = 7 # days
dayLen = 1 # We make the days 1 second long for testing
def onlyOnSunday ():
tt = time.localtime()
exec(open("./Sample.py").read())
t = time.mktime(tt)+dayLen*weekLen
s.enterabs (t,0,onlyOnSunday)
s = sched.scheduler(time.time, time.sleep)
tt = time.localtime()
t = time.mktime(tt)+(6-tt.tm_wday)*dayLen
s.enterabs (t,0,onlyOnSunday)
s.run () # Run all scheduled events
... which uses the method described in the most recent answer to Scheduling a task on python to initially schedule whatever was in Sample.py
to run, exec
ing it as described in an answer to What is an alternative to execfile in Python 3.0?. I'm using Python 3 but if you're using Python 2 you can just use execfile()
directly.
Before the first call to s.enterabs()
, we compute how many days are required to get to next Sunday and schedule the first run for then. Subsequently, we just schedule for the next Sunday by adding a week's worth of seconds to the scheduled time. Note that the next time is calculated from the time obtained immediately after onlyOnSunday()
is first called, so if Sample.py
takes (say) an hour to run we won't have the scheduled time slipping later in the Sunday.
Of course, the 100% Python solution adds a process to the system that wouldn't be needed if cron
was used.