anvil.server.TimeoutError with Background function

What I’m trying to do:
Hi. I’m trying to create a webapp, but one function is taking too long to run and I get the “anvil.server.TimeoutError: Server code took too long” error. I’m NOT using a Free account.

What I’ve tried and what’s not working:
I investigated and learned that the server has a 30 secs time limit for running functions, but you can use a background function to avoid this limit. The thing is, I’m trying to use the background function following this tutorial (Running Tasks in the Background), but this BG function is called by a server function, wich is called from a user-side function, so at the end I’m having the time promblem with the user-side function.

Code Sample:
python

# User-side function
def user_side_click(self, **event_args):
    # code ...
    server_result = anvil.server.call('server_side')
    # code ...


# Server-side function
@anvil.server.callable
def server_side():
    # code ...
    background_result = anvil.server.launch_background_task('background_side')

    while background_result .is_running():  # This line is to wait until the background func. gives a result
        time.sleep(1)
    
    background_result = resumen.get_return_value()  

    # code ...
    return background_result 
 

# Background-side function
@anvil.server.background_task
def background_side():
    # code ...
    # code ...   
    return background_result 


I’m pretty sure I’m doing something wrong, but I can’t get it.
Thanks in advance to anyone who takes the time to answer.

Harold.

If your server function launches the background task and waits for it to end, then you are back at the starting point.

You need to not wait, and instead use a timer to check for the result.

There are many posts that describe how to do it. Here is the first one I found after a quick search: Trigger Timer on function call - #7 by stefano.menci

Let me know if it helps.

3 Likes

Thanks Stefano.

The timer was the secret weapon to fix it all!

1 Like