'Count the duration of a variable in a state (true/false)

I am trying to count the duration of a variable in a specific state (true or false) in seconds then store it in a mongo database, but I can't figure out how to proceed.

Example : if "my_var" is true for 60 seconds, then "my_var_time" = 60 on the database.

I was thinking about running a script that would check "my_var" value each second, but that would not be reliable. It can't work if the program doesn't end in less than one second, which is likely if multiple objects are checked during the process.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source