I have the following code in a class:
def __setattr__(self, key, value):
self.__dict__['d'][key] = value
...
self.saveToIni()
The saveToIni function saves all the dict’s items to an ini file at every object’s setattr call. If 80 setattr calls are made in the last 120ms, then the file will be written from scratch every time. The function also orders and sometimes deletes data from the dictonary, so I don’t want to change it.
I want to limit the calls to once in, let’s say, 5 seconds:
- When the first
setattris triggered, a timer starts asynchronicly, still not runningsaveToIni. - If any calls are made to
setattrand the timer is still counting, it will nor fire a timer nor runsaveToIni. - When the timer times out, the
saveToInishould launch.
Now, I’m not sure how to achieve this behavoir. I’ve thought about messing with threads, but still didn’t found the idea about how to do it.
The way I would go, is to create a Timer Thread which runs a timedSaveToIni function once every 5 sec.
I would also have a tag isSaveRequested telling this function if it should actually write data to the disk or not.
The _setattr_ function would simply set this tag to true.
Your code would look like this: