Datetime object switches values during while loop interations

Viewed 34

I'm seeing this weird issue in my Python code, and not quite sure what is going on. So quick backstory on the code, I've got a function that my UI script calls on startup that runs in a separate thread. This thread is intended to call a function in a separate module that checks to see if the stored timestamp in a database is older than x_value, and does stuff if that's true.

So here's the function (I can post more code later if needed, but this function is where the issue is happening):

def tableUpdateCheck(sensor_manager):
    last_check = datetime.now()
    print(f"last_check: {last_check.strftime('%m/%d/%Y_%H:%M:%S')}")

    while RUN_TABLE_UPDATE_THREAD:
        print(f"Now: {datetime.now().strftime('%H:%M:%S')}\tLast check time: {last_check.strftime('%H:%M:%S')}")
        if datetime.now() - last_check > timedelta(seconds=60):
            print('Running update table update check...')
            sensor_manager.updateTables()
            last_check = datetime.now()

        time.sleep(5)

if __name__ == '__main__':
    sensor_mgr = SensorManager()
    table_thread = Thread(target=tableUpdateCheck, args=[sensor_mgr])
    table_thread.start()
    # Start webserver stuff

The resulting output looks like this:

Now: 17:49:13   Last check time: 17:49:13
Now: 17:49:18   Last check time: 17:49:10
Now: 17:49:23   Last check time: 17:49:13
Now: 17:49:28   Last check time: 17:49:10
Now: 17:49:33   Last check time: 17:49:13
Now: 17:49:38   Last check time: 17:49:10

And continues to do this until the if statement runs, and "last_check" goes back to fluctuating between two values.

Any thoughts on why this might be? It doesn't stop the overall program from ultimately doing what it's supposed to do, but it's super annoying.

1 Answers

So for anyone who might stumble across this in the future, it turns out that "app.run_server(debug=True)" in Flask apps causes an extra thread to run at start. I'm not 100% why this is the case, but that seems to be what's causing the problem I'm describing.

However, using a production Flask app, or simply setting the "debug" argument to False on a development server will not start the multiple threads, and this issue goes away.

Related