looking for a way to run a task starting at a certain time and then repeating every X amount of time afterwards for my bot. For example, run a function at Sunday 7:00pm and then every week afterwards. As it stands I have the current code and am getting the following error shown below, so any help is appreciated. If I'm over-complicating it please let me know, but it would be preferable to use the same libraries and have it be async so it isn't blocking other bot functions, thanks in advance!
import asyncio
from datetime import date, datetime, timedelta
import pytz
days = {
"Monday": 0,
"Tuesday": 1,
"Wednesday": 2,
"Thursday": 3,
"Friday": 4,
"Saturday": 5,
"Sunday": 6,
}
def delay_until(day: str, hour: int):
if (
day.capitalize() not in days
or day.capitalize() != "Tomorrow"
or hour < 0
or hour > 24
):
return "Invalid date provided"
# Get the next day coming up, i.e. the next Monday
today = datetime.now(tz=pytz.utc).date()
if day.capitalize() == "Tomorrow":
target_day = today + timedelta(days=1)
else:
target_day = today + timedelta(
days=(days[day.capitalize()] - today.weekday()) % 7
)
# Add the hours onto the date to make the datetime
full_datetime: datetime = datetime(
year=target_day.year,
month=target_day.month,
day=target_day.day,
hour=hour,
tzinfo=pytz.utc,
)
# Get the time from the target datetime to now in seconds
delta = full_datetime - datetime.now(tz=pytz.utc)
delay: float = delta.total_seconds()
return delay
# Function to schedule a task to run after a given delay and time to loop
async def schedule(delay: float, loop_time: float, function, *args, **kwargs):
await asyncio.sleep(delay)
while True:
await asyncio.gather(function(*args, **kwargs), asyncio.sleep(loop_time))
def time_from_string(time: int, unit: str):
match unit:
case "week":
return time * 604800
case "day":
return time * 86400
def demo_fx():
print("hello world")
async def sample_task():
await schedule(
delay=delay_until("Sunday", 21),
loop_time=time_from_string(1, "week"),
function=demo_fx(),
)
print(asyncio.run(sample_task()))