I would like to set up a system with python3 that would launch a function each time an event is called. I would like to rewrite this javascript code in python
const event = new Event('myevent'); // Listen for the event. elem.addEventListener('myevent', function (e) { /* ... */ }, false); // Dispatch the event. elem.dispatchEvent(event);
I wrote tried this code but the function runs only once
import threading import time event = threading.Event() x = 0 def myFunction(): global x event.wait() if event.is_set(): print("event is set : " + str(x)) x += 1 time.sleep(0.3) th1 = threading.Thread(target=myFunction) th1.start() while True: event.set() time.sleep(1) event.clear()
Advertisement
Answer
First I will post the right code to solve your problem and then I will explain.
import threading import time event = threading.Event() x = 0 def myFunction(): global x while True: event.wait() if event.is_set(): print("event is set : " + str(x)) x += 1 event.clear() th1 = threading.Thread(target=myFunction) th1.start() while True: event.set() time.sleep(1)
An Event object is a mechanism used for communication between threads. event.wait()
will wait until the flag is set to sent a signal to thread/s it has been subscribed by. Every time event.wait()
is called inside a thread, the thread pauses there until the event’s set flag is set.
So if you want to run the
if event.is_set(): print("event is set : " + str(x)) x += 1
block repeatedly, You have to call event.wait()
repeatedly once per second. So you have to put it inside a while loop.
The second place where you have done wrongly is , you try to clear the flag inside the same while loop you used to set it. You have to reset the flag just right after the code block was run. So you must place event.clear()
just after x += 1
. And remove the time.sleep(0.3)
line from code.
The result is
event is set : 0 event is set : 1 event is set : 2 event is set : 3 event is set : 4 event is set : 5 event is set : 6 event is set : 7 event is set : 8 event is set : 9 .......