I want my function delayed_sum(value, delay)
to add the value
to a global variable result
with a certain delay
in Python 3.x.
The idea is to connect my Python code with Electron to have a user interface. The user interface lets you view this global variable called result
and let's you add some value
to result
with a certain delay
expressed in seconds.
I would like the variable result
to be updated as soon as the delay has elapsed and while the function is running in the background, still be able to call the function.
If we have the time in seconds as follow:
- Initialisation of
result
to 0 and display of 0 on the UI delayed_sum(5, 10)
called. In 10 seconds, add 5 to result- Add 5 in 9 seconds
- Add 5 in 8 seconds
- Add 5 in 7 seconds
- Add 5 in 6 seconds
- Add 5 in 5 seconds
- Add 5 in 4 seconds
- Add 5 in 3 seconds and
delayed_sum(3, 5)
called. In 5 seconds, add 3 to result - Add 5 in 2 seconds and in 4 seconds add 3
- Add 5 in 1 second and in 3 seconds add 3
result += 5
and the UI displays 5 and in 2 seconds add 3- In 1 second add 3
result += 5
and the UI displays 8
I tried using time.sleep()
but it freezes the control panel and I'm not able to call delayed_sum()
while a first delayed_sum
is being executed.
import time
import threading
result = 0
def delayed_sum(value, delay):
t = threading.Thread(target=perform_sum, args=(value,delay,))
t.start()
def perform_sum(value, delay):
global result
time.sleep(delay)
result += value
When I use the code above, the action is indeed performed, but the result
value isn't updated in the variable explorer before an other command line is executed.
I still haven't used Electron, but I'm afraid that if I ask my UI to read the value of result
, what will be displayed won't be in real time. Could you guide me in making sure the UI will indeed read the correct value of result
?
Many thanks!