Python return value from scheduled event


I would like to get the value returned from a function called by a scheduled event. Below is a simple example of what I would like to do.

import time
import sched

schedule = sched.scheduler(time.time, time.sleep)

def ret_this():
    return "This."

def schedthis():
    schedule.enter(2,1,ret_this, ())
    ## <- print returned value here

if __name__ == "__main__":

I have tried many things like:

     schedule.enter(2,1,print ret_this, ())

or even:

    schedule.enter(2,1,ret = ret_this, ())
    print ret

Maybe some background will be necessary.

I would like to create a server that will listen for incoming connections(This is done.). When a connection is established a new thread will spawn and the socket will be parsed to that thread. On that thread the values sent to the server will be read and the server will judge what the client is trying to schedule. Once the server knows what the client wants it will schedule it.

If the user wants to view the information after the scheduled event has completed (Where this answer comes in) then it will wait until the event has ended and send the returned values to the client.

If not the the event will be scheduled and the client will receive “Done, farewell.” and the connection will close.

I call the programming gods, please could you help me.

Asked By: Warosaurus



The problem is actually prety simple. You’re returning something from the ret_this function, but you didn’t put it anywhere, nor printing it!

Please see this

Turns out that the code i posted earlier only executes the function, not when it’s run by the scheduler.
Since only runs a function without actually care about the value it returns, you’ll have to store it somewhere to actually know when it’s called.

For example, in a global variable:

def ret_this():
    global result
    result = "I'm called!"

Or just print it from ret_this:

def ret_this():
    print "This."

Edit 2
Another way to store it is writing it in a file. You can read it again later:

def ret_this():
    with open('output.txt', 'w') as f:
        f.write('I am called!')

if __name__ = "__main__":
    with open("output.txt", 'r') as f:

If the execution was succesful, your file will contain I am called!. Else, it will be empty.

Hope this helps!

Answered By: aIKid

Well, I am not really happy with the most helpful answer yet,
saving the result to a file…

The result value could be saved into a mutable object e.g. I took a list to demonstrate the quick-and-dirty workaround:

#!/usr/bin/env python3

import sched, time

def foo(l:list[str]):

    # do some stuff...

    # append the result to the "return list"

l:list[str] = list()

s = sched.scheduler(time.time, time.sleep)
s.enter(5, 1, foo, argument=(l,))

if l:
Answered By: Gabriele Iannetti