Reset recording timer if it called a second time

I am trying to create a system in which the trigger fires, so the doors open for 5 seconds and then close again. I am using Threading.Timer to do 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 some door, wait 2 seconds, then open another door, everything closes after 3 seconds. How can I reset the timer?

+4
source share
2 answers

You can change the timer every time you open the door, for example

 mytimer.Change(5000, 0); // reset to 5 seconds 
+8
source

You can do something like this:

 // First off, initialize the timer _timer = new System.Threading.Timer(OnTimedEvent, null, Timeout.Infinite, Timeout.Infinite); // Then, each time when door opens, start/reset it by changing its dueTime _timer.Change(5000, Timeout.Infinite); // And finally stop it in the event handler void OnTimedEvent(object obj) { _timer.Change(Timeout.Infinite, Timeout.Infinite); Console.WriteLine("All doors are closed because of timer"); } 
+2
source

Source: https://habr.com/ru/post/1486247/


All Articles