I'm trying to create a system where a trigger happens so doors open for 5 seconds, and then close again. I'm using Threading.Timer for this, using:
OpenDoor();
System.Threading.TimerCallback cb = new System.Threading.TimerCallback(OnTimedEvent);
_timer = new System.Threading.Timer(cb, null, 5000, 5000);
...
void OnTimedEvent(object obj)
{
_timer.Dispose();
log.DebugFormat("All doors are closed because of timer");
CloseDoors();
}
When I open a certain door, the Timer starts. After 5 seconds, everything closes again.
But when I open a certain door, wait 2 seconds, then open another door, everything closes after 3 seconds. How can I 'reset' the Timer?
Once created, the thread must be started by calling the start() function which will begin the timer. If we decide to cancel the timer before the target function has executed, this can be achieved by calling the cancel() function.
Timer is a sub class of Thread class defined in python. It is started by calling the start() function corresponding to the timer explicitly. Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed.
Python timer functions To end or quit the timer, one must use a cancel() function. Importing the threading class is necessary for one to use the threading class. The calling thread can be suspended for seconds using the function time.
Timer is not thread-safe. Since then this has been repeated on blogs, in Richter's book "CLR via C#", on SO, but this is never justified.
Do not dispose the timer, just change it every time you open a door, e.g.
// Trigger again in 5 seconds. Pass -1 as second param to prevent periodic triggering.
_timer.Change(5000, -1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With