Can't get my app to work everyday! I user time.sleep() for > 12 hours

44 views Asked by At

I am writing a script which sends facebook messages telling sunrise and sunset times. The times are sent at 10 a.m. to a list of receivers. The way I figure out the timing is: When the script runs I get the time, then I scrape the sunrise/sunset times from a web page, calculate how much time until the soonest one (let's say sunrise), sleep for that time then send the message, then sleep until sunset and send another message, etc. The script works for the first message, but not for the second. After sending the first message, it displays how long it will sleep for until the second message, and it is always the correct amount of time, however, it does not seem to wake up from that sleep. Any ideas on what is happening here/ is there a better way to accomplish the task?

from fbchat import Client
import sunset2
import time

email, password = [********, ********]

client = Client(email, password)
receivers = [receiver1 , receiver2, receiver3, receiver4] # Fb friends names
while True:
    # Check out the get_msg() function below
    # Get the appropriate message and send it to all receivers
    msg = sunset2.get_msg(url)
    for receiver in receivers:
        client.send(Message(text = msg), thread_id = receiver,         
                                                thread_type=ThreadType.USER)
    time.sleep(60) # sleep for a minute so that you don't send more than one message to the users


def get_msg(url):
    # Calculate the time to the sunrise and sunset, pick the smallest and return a message accordingly        

    # get sunrise and sunset times from another function
    sunrise, sunset = get_sunrise_sunset(url)
    now = datetime.datetime.now()
    t_now = now.strftime("%I:%M %p")

    until_sunset = diff(t_now, sunset)  # get difference in seconds
    until_10 = diff(t_now, '12:00 PM')  # get difference in seconds

    wait_time = min(until_sunset, until_10)
    
    # for debug
    print('{}:{} left!'.format(wait_time //3600, wait_time //60%60))
    
    time.sleep(rem - 20) # 20 seconds earlier because sending the messages takes about 20 seconds

    if until_sunset < until_10:
        return 'It's sunset!!'
    else:
        return f'Sunset today: {sunset}\nSunrise today: {sunrise}'
1

There are 1 answers

0
coltonrusch On

You could try using this lightweight Python library called schedule to handle the scheduling instead.