schedule icon indicating copy to clipboard operation
schedule copied to clipboard

How to handle jobs that return values?

Open saketvora opened this issue 3 years ago • 2 comments

Sorry in advance if this is already documented somewhere, can't find it yet.

I have functions that return values, and I'm struggling to see how to factor that into the way you schedule and run jobs with this library. Example, a function called getData() that does a API get request, and returns a variable called data Then a function called processData(data) that takes the data and does something with it.

In my example, I'd like to only run getData() once every 48 hours, but I need to run processData(data) every hour. (The reason for this is that the data feed via API doesn't refresh very often, so I don't need to call it every hour).

I see the syntax for defining the scheduling parameters be:

schedule.every(48).hours.do(getData)
schedule.every(1).hours.do(processData)

but how do I handle the data variable returned by getData()

All the examples I've found so far with schedule are jobs that don't return values. If I need my jobs to share data with each other, maybe I need to use global variables?

Any help much appreciated, thanks.

saketvora avatar Sep 29 '22 21:09 saketvora

One way to get around of this is the function access the outer scope (such as the global scope)

getData could access a variable to update it's value, and processData could do the same to read this value. With a 'wrapper' of any kind (a dict, list or class), you can do this with less chance of messing with references.

See an example:

import schedule

class Wrapper:
    value = None

data = Wrapper()

def getData():
    print("Getting new data...")
    data.value = 'the new data'

def processData():
    print("I'm processing... current value:")
    print(data.value)

schedule.every(8).seconds.do(getData)
schedule.every(5).seconds.do(processData)

gabrielcipriano avatar Oct 10 '22 22:10 gabrielcipriano

yup, this type of wrapper worked for me and it is a good thing to have. I have significantly more complex scenario with, rpc, statemachine, scheduler, and multi processing but at the end I got result of operation finally back to caller ...

thanks for the hint ...

catchthemonster avatar Mar 27 '24 19:03 catchthemonster