First of all, I will completely get rid of the control thread, because its work can be easily done before calling work() .
Then I will make the workflow different from the main thread, thereby unlocking the main thread for other tasks. Then I would add a function to cancel processing that might have set the flag marked by the workflow.
Edit:
According to the comments, our goal is to limit the number of work() calls during each throttlePeriod tag. We can do this better by noting the time in the stopwatch by comparing it after throttleLimit work operations and the remaining time remaining. Thus, we again do not need a timer thread.
Edit: (deleted, it was incorrect)
Edit:
We can even do some balancing: being within the throttlePeriod , we calculate how much time work() did, so we can estimate hw a lot of time, all the remaining work() are going to take, and wait between each two work() equal shares time remaining. This will force us not to execute all work() very quickly at the beginning of the allocated period, possibly blocking the database.
source share