Skip to content
Advertisement

How Can I create an event that run a function each time the event is set?

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

JavaScript

I wrote tried this code but the function runs only once

JavaScript

Advertisement

Answer

First I will post the right code to solve your problem and then I will explain.

JavaScript

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

JavaScript

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

JavaScript
Advertisement