Chris Angelico <ros...@gmail.com> writes: > On Thu, 3 Feb 2022 at 15:43, Cecil Westerhof via Python-list > <python-list@python.org> wrote: >> >> Chris Angelico <ros...@gmail.com> writes: >> >> >> > (Side point: The OP's code is quite inefficient, as it creates a new >> >> > thread for each reiteration, but there's nothing wrong with that if >> >> > you're looking for something simple.) >> >> >> >> It is just something I wrote fast. How could I do this in a better way? >> > >> > I'll answer your question, but first and foremost: Your code was fine, >> > and if something does what it's supposed to, that is the most >> > important. Everything else is minor. >> >> I like to write efficient code and it never hurts to write better code >> as just doing what it is supposed to do. ;-) >> >> And in my case interval is .5 seconds and when someone is going to use >> it with an even smaller interval … >> >> >> > But for other ways to do things, I would recommend creating a single >> > thread function and spawning a single thread to run it, and then >> > having that function call the target every N seconds. Also, consider >> >> Have to be careful that timing keeps correct when target takes a 'lot' >> of time. >> Something to ponder about, but can wait. > > Ah. In that case, I would recommend a different look at things. > Instead of waiting X time, then firing the event, then waiting X time, > consider instead an interval timer based on monotonic time: > > https://docs.python.org/3/library/time.html#time.monotonic > > When the timer starts, record the current monotonic time, and sleep > one interval. After the function returns, sleep the remainder of one > interval. It's up to you what happens if you ever find that the next > time point has already passed - do you call the function immediately, > or skip and wait for the next moment? > > Interval timers have some complexity to them, but it's worth putting > in the time (pun intended) to figure out how these things work :)
I will look into it. -- Cecil Westerhof Senior Software Engineer LinkedIn: http://www.linkedin.com/in/cecilwesterhof -- https://mail.python.org/mailman/listinfo/python-list