Search code examples
pythoncronschedule

Start and stop a Python script at a specific time


I am writing a script which will record the user activity in a certain period of time every day. The periods are taken from a JSON response of an API, like this:

[{"working_day": "mon", "work_start_at": "09:00", "work_end_at": "18:00"},
{"working_day": "tue", "work_start_at": "09:00", "work_end_at": "15:00"}]

Let's assume that I can parse these strings in a datetime() format. I want to run my function accordingly to these periods and stop my function after "work_end_at". I found numerous example of how to run after certain amount of seconds, how to run every day (Python lib schedule) and examples with bash crontab. But nothing of this works for me, because all I want is to start the script at a specific time and stop at a specific time. And then, run again when the next "shift" comes.

def start():
    time_periods = working_periods_table.find_all()
    today = datetime.datetime.now().isoweekday()
    for day in time_periods:
        if day["day"] == today:
            start_time = day["work_start_at"]
            end_time = day["work_end_at"]

    schedule.every().week.at(start_time).do(record_activity(idle_time=300))

Solution

  • If I've understood what you're asking, you could use while loops. Have it periodically check the current time with the times for the shift beginning and end. Below is a guide of what I mean, but I'm not sure the comparisons will work.

    from time import sleep
    
    def start():
        time_periods = working_periods_table.find_all()
        today = datetime.datetime.now().isoweekday()
        for day in time_periods:
            if day["day"] == today:
                start_time = day["work_start_at"]
                end_time = day["work_end_at"]
    
        while True:
            if datetime.datetime.now() >= start_time:
                while True:
                    schedule.every().week.at(start_time).do(record_activity(idle_time=300))
                    if datetime.datetime.now() >= end_time:
                        break
                break
            else:
                sleep(100)