-1

I'm calling a function in micropython which I know may stall and force me to restart the script.

How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?

1 Answers1

0

For your task, probably you should go with Threads or Asyncio. Hre is a sample of aasyncio approach

Not tested

import uasyncio


async def call_api(message, result=1000, delay=3):
    print(message)
    await uasyncio.sleep(delay)
    return result


async def main():
    task = uasyncio.create_task(
        call_api('Calling API...', result=2000, delay=5)
    )

    MAX_TIMEOUT = 3
    try:
        await uasyncio.wait_for(task, timeout=MAX_TIMEOUT)
    except uasyncio.TimeoutError:
        print('The task was cancelled due to a timeout')

uasyncio.run(main())

Read more about micropython uasyncio here

Lixas
  • 6,938
  • 2
  • 25
  • 42