[Django]-Why is Idle Python Thread Consuming upto 90% of CPU?

4👍

cron_thread has an infinite loop. This loop first retrieves scheduled actions, then loops over them. For each action, if the action is scheduled for the exact current time, the action is executed.

If no actions are scheduled, the loop will simply keep retrieving the scheduled actions, over and over again. If there is an action, it will check whether now is the time to execute it. Here’s another problem: datetime.datetime.now() has very high precision (nearest microsecond), so the chances that it’ll match the scheduled time for an action are very low. This means your loop will retrieve all scheduled actions, loop over all the actions, and then go back to the top.

On the off-chance that a scheduled action’s time does match the current time, that action will be executed, then the inner loop moves onto the next action. When it’s looped through all the actions, it will go back to the top and retrieve all actions once again.

Basically, your program is constantly comparing any scheduled actions to the current time. That takes processing power. A better way to execute these actions would be to check the time for each new action as it’s added to the list of tasks, calculate the necessary delay until that action needs to be executed, and then set a timer to execute that action after the necessary delay (time.sleep in a thread, after calls in tkinter, that sort of thing).

Leave a comment