0

I have a executor that executes phone calles according to what user specifies.
I want to schedule time only in specific range of hours during the day, for example from 8AM to 6PM.
The executor is working 24 hours per day and is checking records in database whether to execute a phone call or not at the moment.
Is there any tricky way to schedule future calls by using python's datetime and setting somehow these working hours with given frequency and number of calls.
For example I want to schedule 4 calls with 1 hour frequency. Let's say it's 4PM. Next call should be scheduled on 4PM, 5PM and next one - next day at 8AM, 10AM.
I'd expect datetime to work in this conditions like below:

def schedule(no_of_calls: int, frequency: timedelta):
  dt = get_a_magic_datetime_with_hour_range()
  value = dt.now()  # this will get 4PM in above's example. Though if it would be 10PM it would return 8AM next day.
  for i in range(no_of_calls):
    save_to_db(value)
    value += frequency    

I know I could create my own working_datetime which would make proper validations and return values from within range of working hours, but maybe there is already something like this.

If you still don't get the idea - think of this like of parking meter - if you pay outside of paying hours - it will count from the start of paying hours next day (or same if it's past 12AM).

Marek
  • 1,189
  • 3
  • 13
  • 33

1 Answers1

0

The code should be sufficiently self-explanatory: it does nothing except "something" at 8 AM, 9 AM ... 5 PM of everyday, starting from Mon 20 Jan 2020.

Note that I didn't tested it, but at least in principle the strategy should be a viable one. I checked the various if conditions and update rules, but check them again before launghing an infinite loop such as this one.

#!/usr/bin/env python

'''
This code performs a certain (generic) action
every hour, from 8 AM to 5 PM of everyday, starting
from next monday, that is 20 Jan 2020.

This means the code performs 10 actions per day
and then does nothing for the next 14 hours.

Temporal precision is seconds.
'''

import time
from datetime import datetime

str_begin = 'Jan 20 08:00:00 +0000 2020'
next_action = int(datetime.timestamp(datetime.strptime(str_begin, '%b %d %H:%M:%S %z %Y')))  # Unix timestamp


one_hour = 3600                         # Number of seconds in an hour
waiting_time = 14 * one_hour

daily_count = 0

now = int(datetime.timestamp(datetime.now()))
while True:
    if now == next_action:

        # Make a call or whatever

        daily_count += 1
        if daily_count < 10:
            next_action += one_hour
        if daily_count == 10:              # At 5 PM daily_count will be 10 and next_action will be 6 PM. You reset the count and next_action to 8 AM.
            daily_count = 0
            next_action += waiting_time

    now = int(datetime.timestamp(datetime.now()))

GRquanti
  • 527
  • 8
  • 23