Search code examples
pythonmultithreadingtwistedpython-multithreading

Is it possible to force a 2 second looping callback in Python?


I'm trying to get a looping call to run every 2 seconds. Sometimes, I get the desired functionality, but othertimes I have to wait up to ~30 seconds which is unacceptable for my applications purposes.

I reviewed this SO post and found that looping call might not be reliable for this by default. Is there a way to fix this?

My usage/reason for needing a consistent ~2 seconds:

The function I am calling scans an image (using CV2) for a dollar value and if it finds that amount it sends a websocket message to my point of sale client. I can't have customers waiting 30 seconds for the POS terminal to ask them to pay.

My source code is very long and not well commented as of yet, so here is a short example of what I'm doing:

#scan the image for sales every 2 seconds
def scanForSale():
    print ("Now Scanning for sale requests")

#retrieve a new image every 2 seconds
def getImagePreview():
    print ("Loading Image From Capture Card")

lc = LoopingCall(scanForSale)
lc.start(2)

lc2 = LoopingCall(getImagePreview)
lc2.start(2)

reactor.run()

I'm using a Raspberry Pi 3 for this application, which is why I suspect it hangs for so long. Can I utilize multithreading to fix this issue?


Solution

  • Raspberry Pi is not a real time computing platform. Python is not a real time computing language. Twisted is not a real time computing library.

    Any one of these by itself is enough to eliminate the possibility of a guarantee that you can run anything once every two seconds. You can probably get close but just how close depends on many things.

    The program you included in your question doesn't actually do much. If this program can't reliably print each of the two messages once every two seconds then presumably you've overloaded your Raspberry Pi - a Linux-based system with multitasking capabilities. You need to scale back your usage of its resources until there are enough available to satisfy the needs of this (or whatever) program.

    It's not clear whether multithreading will help - however, I doubt it. It's not clear because you've only included an over-simplified version of your program. I would have to make a lot of wild guesses about what your real program does in order to think about making any suggestions of how to improve it.