Time.sleep in anvil

Hi guys!

I’m trying to make a loop in a server module where the While loop will run all the time (this is required) but will have a delay of some time, say 5 seconds.

I decided to implement it the way I do locally in python 3 using time.sleep.

Server module code:

def getActualPrice(ticker):
  while 1:
    r = requests.get(f'https://api.binance.com/api/v3/ticker/price?symbol={ticker}')
    price = r.json()['price']
    time.sleep(5)
  return price

But when starting the preview and executing this part of the code, the application just lagging and gives the following error: “anvil.server.TimeoutError: Server code took too long”

It seems to me that anvil simply does not support time.sleep and, accordingly, simply loops an infinite loop and hangs without paying attention to time.sleep (import time is present).

Who faced, is there a solution?

Welcome!

That’s not the way server modules in Anvil work. Server modules are spun up for every server call, and then go away. The server call must finish in 30 seconds.

What you want is a scheduled task: Anvil Docs | Scheduled Tasks Scheduled tasks allow you to run a server function (a background task) every X minutes, or on some other schedule.

1 Like

I just want to add, (this is a common topic on the forum) there are some functions of the built in time module like .sleep() that seem to be disabled in the free version of the server module. If you have the Full Python3 version it seems to work.

image

1 Like

The return appears to be outside of the while loop. So the return can’t be reached. This function would never finish. At best, it would raise an error.

1 Like

Thank’s a lot, Guys!