Timer inaccurate - c#

I am trying to implement a delay of 10 seconds before calling a a method. However, the method is being called in just one second.
private void closeDoors(Floor floor)
{
Timer timer = new Timer();
timer.Interval = 10000;
timer.Tick += delegate
{
DoorManager(floor, Operation.CLOSE, null);
};
timer.Start();
}
Where am I going wrong?
Thank you for your assistant.

Your problem may occur because of not stopping the Timer after finishing its job. The following modified code should work (as long as I've experienced with Timer):
private void closeDoors(Floor floor) {
Timer timer = new Timer();
timer.Interval = 10000;
timer.Tick += (s,e) => {
DoorManager(floor, Operation.CLOSE, null);
((Timer)s).Stop();
};
timer.Start();
}

I manage to fix it by incrementing the timer Interval as the time delay was being utilised by a process invoked by another method call insideDoorManager().

Related

How to avoid timer speeding up when called more than once in C#

When this function is called twice to restart the timer, the timer speeds up and goes twice as fast when called twice. How to avoid this?
public void SetTimer(PlanetarySystem nPlanetsAndSun, int duration, int simulationTimeInterval)
{
this.simulationTimeInterval = simulationTimeInterval; //milliseconds (dt provided by the user)
timer = new System.Timers.Timer(simulationTimeInterval); //Create a timer
timer.Elapsed += UpdatePlanetsAndSimulationTime; //Sets which method to call when timer elapses
timer.Enabled = true;
timer.Start();
this.nPlanetsAndSun = nPlanetsAndSun;
this.duration = duration; //milliseconds
}
'''
Change your code to:
if (timer == null) {
timer = new System.Timers.Timer(simulationTimeInterval); //Create a timer
timer.Elapsed += UpdatePlanetsAndSimulationTime; //Sets which method to call when timer elapses
timer.Enabled = true;
timer.Start();
}
If you ever stop / dispose your timer, make sure to also set it to null
timer?.Dispose();
timer = null;
You could also dispose the old timer at the start of SetTimer
System.Timers.Timer (or their callback Handle) will be automatically added to some global static collection when you create them so don't try to override a timer. It won't stop the old one...

C# and how to use "System.Timers"

I recently started to use C# and I wanted to use timers.
I read Windows help about how to declare and define a Timer.
What I don't understand is why I need the Console.ReadLine(); line to start the timer.
(Link to the example)
// Firstly, create a timer object for 5 seconds interval
timer = new System.Timers.Timer();
timer.Interval = 5000;
// Set elapsed event for the timer. This occurs when the interval elapses −
timer.Elapsed += OnTimedEvent;
timer.AutoReset = false;
// Now start the timer.
timer.Enabled = true;
Console.ReadLine(); // <------- !!!
What I want to do but I don't achieve is to start the timer as soon as it is declared. I dont want to write Console.ReadLine(); because I may not need a console.
Example: If i develop a timer class and I call it from an other class, how can I check the timer has been completed?
Thank you in advance.
You need to set Timer, than wait for time is elapsed which executes the OnTimedEvent, that is how you can check if it already elapsed.
// Create a timer with a two second interval.
timer = new System.Timers.Timer(2000);
// Hook up the Elapsed event for the timer.
timer.Elapsed += OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
The OnTimedEvent should look like this:
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
e.SignalTime);
}
If you need to Stop the timer you should call:
timer.Stop();
timer.Dispose();
You need Console.ReadLine(); just for not exiting the main method and the whole program. If you're developing something else like MVC or WPF, you don't need it.

Is it possible to change Timer Tick in the middle of running

I have application that execute some task via Timer every new minutes and i want to add the option to make this task changeable using user input in the middle of application running.
if for example my Timer.Tick is set to 1 minute and changed into 1 hour, Timer.Tick property will update ir i need to restart my application ?
I just ran this in LINQPad and it 'ticks' every second after I change the interval, meaning it looks like it respects your change to the interval property immediately.
void Main()
{
var timer = new System.Windows.Forms.Timer();
timer.Tick += Timer_Tick;
timer.Interval = 50000;
timer.Start();
System.Threading.Thread.Sleep(1000);
timer.Interval = 1000;
}
private void Timer_Tick(object sender, EventArgs e)
{
Console.WriteLine("Tick");
}
I'm assuming you are using System.Windows.Forms.Timer based on you referencing the Tick event. I also ran the same test using System.Threading.Timer and saw the same results.

Fire timer_elapsed immediately from OnStart in windows service

I'm using a System.Timers.Timer and I've got code like the following in my OnStart method in a c# windows service.
timer = new Timer();
timer.Elapsed += timer_Elapsed;
timer.Enabled = true;
timer.Interval = 3600000;
timer.Start();
This causes the code in timer_Elapsed to be executed every hour starting from an hour after I start the service. Is there any way to get it to execute at the point at which I start the service and then every hour subsequently?
The method called by timer_Elapsed takes too long to run to call it directly from OnStart.
Just start a threadpool thread to call the worker function, just like Timer does. Like this:
timer.Elapsed += timer_Elapsed;
ThreadPool.QueueUserWorkItem((_) => DoWork());
...
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
DoWork();
}
void DoWork() {
// etc...
}
Use AutoReset Property of System.Timers.Timer and set it value to "true".
No need to use timer.Start() because it does the same job as timer.Enabled = true;
timer = new Timer();
timer.Elapsed += timer_Elapsed;
timer.Enabled = true;
timer.Interval = 3600000;
timer.AutoReset = true;
AutoReset = true will set a value indicating that the Timer should raise the Elapsed event each time when the specified interval elapses.
If you want your Timer to be fired immediately then you could simply just initialize the Timer object without a specified interval (it will default to 100ms which is almost immediately :P), then set the interval within the called function to whatever you like. Here is an example of what I use in my Windows Service:
private static Timer _timer;
protected override void OnStart(string[] args)
{
_timer = new Timer(); //This will set the default interval
_timer.AutoReset = false;
_timer.Elapsed = OnTimer;
_timer.Start();
}
private void OnTimer(object sender, ElapsedEventArgs args)
{
//Do some work here
_timer.Stop();
_timer.Interval = 3600000; //Set your new interval here
_timer.Start();
}
Use System.Threading.Timer class instead of System.Timers.Timer as this type is just a wrapper for Threading Timer.
It also suits your requirement.
System.Threading.Timer timer =
new System.Threading.Timer(this.DoWork, this, 0, 36000);
Here are the details.

How to stop a timer after it is done running?

I have a Console App and in the main method, I have code like this:
Timer time = new Timer(seconds * 1000); //to milliseconds
time.Enabled = true;
time.Elapsed += new ElapsedEventHandler(time_Elapsed);
I only want the timer to run once so my idea is that I should stop the timer in the time_Elapsed method. However, since my timer exists in Main(), I can't access it.
You have access to the Timer inside of the timer_Elapsed method:
public void timer_Elapsed(object sender, ElapsedEventArgs e)
{
Timer timer = (Timer)sender; // Get the timer that fired the event
timer.Stop(); // Stop the timer that fired the event
}
The above method will stop whatever Timer fired the Event (in case you have multiple Timers using the same handler and you want each Timer to have the same behavior).
You could also set the behavior when you instantiate the Timer:
var timer = new Timer();
timer.AutoReset = false; // Don't reset the timer after the first fire
A little example app:
static void Main(string[] args)
{
int seconds = 2;
Timer time = new Timer(seconds * 1000); //to milliseconds
time.Enabled = true;
time.Elapsed += new ElapsedEventHandler(MyHandler);
time.Start();
Console.ReadKey();
}
private static void MyHandler(object e, ElapsedEventArgs args)
{
var timer = (Timer) e;
timer.Stop();
}
I assume that you're using System.Timers.Timer rather than System.Windows.Forms.Timer?
You have two options.
First, as probably the best, is to set the AutoReset property to false. This should do exactly what you want.
time.AutoReset = false;
The other option is to call Stop in the event handler.
You may also use the System.Threading.Timer. Its constructor takes two time-related parameters:
The delay before the first "tick" (due time)
The period
Set the period to Timeout.Infinite to prevent from firing again.

Categories