Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting Threading Timer if it's called a second time

Tags:

c#

timer

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?

like image 226
Joetjah Avatar asked Jun 14 '13 13:06

Joetjah


People also ask

How do I cancel thread 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.

How do I start a thread timer?

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.

How do I stop a countdown in Python?

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.

Is system threading timer thread-safe?

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.


1 Answers

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); 
like image 91
TheNextman Avatar answered Sep 16 '22 15:09

TheNextman