I thought I'd chime in with a way to do this in python, since you said that the only reason you're looking at crontab is because you couldn't figure out how to do it in python.
I'm using the library apscheduler which allows you to schedule your python scripts for run time later.
Here's an example that schedules a job for either 1a or 1p (whichever is next) and will end at 6a or 6p, respectively. When the job is finished it calls main() again which schedules the next job:
import datetime
from apscheduler.schedulers.background import BackgroundScheduler
def job_function():
"""Worker function that will be called at 1a or 1p everyday"""
while True:
if datetime.datetime.now().time() >= endtime:
main()
break
def main():
"""Main function that determines what time it is and when job_function() should be run next"""
earlystart = datetime.time(hour=1)
latestart = datetime.time(hour=13)
now = datetime.datetime.now()
global endtime
if earlystart < now.time() > latestart:
tomorrow = now.date() + datetime.timedelta(days=1)
startdate = now.replace(day=tomorrow.day, hour=earlystart.hour, minute=0, second=0, microsecond=0)
endtime = datetime.time(hour=6)
else:
if datetime.datetime.now() < earlystart:
starthour = earlystart
endtime = datetime.time(hour=6)
else:
starthour = latestart
endtime = datetime.time(hour=18)
startdate = now.replace(hour=starthour.hour, minute=0, second=0, microsecond=0)
scheduler.add_job(job_function, 'date', run_date=startdate)
if __name__ == '__main__':
scheduler = BackgroundScheduler()
scheduler.start()
main()
Let me know if you have any questions.
start_time = time.time()once and thencurrent_time = time.time()periodically. and keep checking if its 6 hours.