Can't seem to use the 'sched' module the way I want it to work

163 Views Asked by At

The python project I'm working on, is a webpage that outputs covid data and news at a scheduled time. The project must use the sched module.

The issue I'm having it to do with schedule_covid_update() function. When calling the function. You have 2 required argument, the duration/time for the update to occur, the name of the update. And the 2 optional arguments, news and data. Which are used to tell schedule_covid_update() if both or just one update type is occurring at the scheduled time.

Now, if I were to call the function twice like this for example:

schedule_covid_update(4, "test update 2", news="news", data="data")
schedule_covid_update(0, "test update 1", news="news", data="data")

I would expect the data for "test update 1" to occur and return the data before "test update 2", regardless of the order I called schedule_covid_update(). But It doesn't, it schedules "test update 2".

Also when testing this code. You can just try some other function instead of updateData and updateNews. As I can't give the code for the functions.

scheduler.py:

import time, sched
from datetime import datetime
from covid_data_handler import *


s = sched.scheduler(time.time, time.sleep)
def schedule_covid_update (update_interval, update_name, news="", data=""):
    print("update name: " + update_name)

    if(news=="news" and data=="data"):
        #s.enter(timeDuration(update_interval),1, updateData)
        #s.enter(timeDuration(update_interval),1, updateNews)
        s.enter(update_interval,1, updateData)
        s.enter(update_interval,1, updateNews)
        print("Updating news and data")
    elif(news=="news" and data!="data"):
        #s.enter(timeDuration(update_interval),1, updateNews)
        s.enter(update_interval,1, updateNews)
        print("Updating news only")
    elif(news!="news" and data=="data"):
        #s.enter(timeDuration(update_interval),1, updateData)
        s.enter(update_interval,1, updateData)
        print("Updating data only")
        #scheduler.run(blocking=False)
    else:
        print("No Update")

    s.run()


schedule_covid_update(4, "test update 2", news="news", data="data")
schedule_covid_update(0, "test update 1", news="news", data="data")
1

There are 1 best solutions below

0
Dominik Stańczak On

Take a look at the docs for scheduler.run . With s.run() inside of your function, it blocks forever and never reaches the second scheduled task. Schedule first, then run the scheduler independently, outside of the scheduling functions.