C# Timer firing too early - c#

When I call the Method random_Start() it works at first: The second console print comes at a reasonable time, but then the gap between the console prints gets smaller and smaller.
After some prints, almost every print comes after way less than 5 Seconds, although the code should set a Timer for at least 5 Seconds, right?
static Timer timer;
static Random random = new Random();
public static void random_Start()
{
timer = new Timer(random.NextDouble()*10000+5000);
timer.Elapsed += OnTimedEvent;
timer.Start();
Console.WriteLine("Start");
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
random_Start();
}

Setup your timer so that you aren't creating a new instance with every timer tick. In the example below, I've disabled AutoReset so that we can set a new interval and start the timer again manually.
static Timer timer;
static Random random = new Random();
public static void random_Start()
{
timer = new Timer(random.NextDouble()*10000+5000);
timer.Elapsed += OnTimedEvent;
timer.AutoReset = false;
timer.Start();
Console.WriteLine("Start");
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Console.WriteLine("Tick");
timer.Interval = random.NextDouble()*10000+5000;
timer.Start();
}

Related

How to delay a timer from running or start it based on current date time

I have console application am using as demo to an App, it prints "hello", based on the timespan its expected to alert the user. when its not yet the timespan, i want to delay the app from printing hello and resume when its time.
public static async void timeCounter(int delae)
{
//This is suppose to cause a delay but it instead initiate the
//TimerOperation_Tick method.
await Task.Delay(delae);
// timer countdown
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000; // 1 second
timer.Elapsed += new ElapsedEventHandler(TimerOperation_Tick);
timer.Start();
if (obj.SubmissionCheck == true)
{
timer.Stop();
}
}
/// the event subscriber
private static void TimerOperation_Tick(object e, ElapsedEventArgs args)
{
if (timeFrame != 0)
{
Console.WriteLine("hi" + timeFrame);
timeFrame --;
if (timeFrame < 1)
{
obj.SubmissionCheck = true;
nt.Remove(obj);
startNotification();
}
}
}
Try setting timer.Enabled = false; This will prevent the timer ticks from occurring.

Creating a countdown timer,until a timer starts

I have a timer in a console app:
using System.Timers;
Timer Timer = new Timer();
I gave it an interval, and it does stuff at _timer_Elapsed method periodically:
Timer.Elapsed += _timer_Elapsed;
Timer.Enabled = true;
private static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
...
}
How can I create a second timer that counts down until this timer starts?
Create a second timer that elapses every second and use the following code to count down and a write message to the console.
#define COUNTDOWN_SECONDS 10
private int CountDownValue = COUNTDOWN_SECONDS;
private static void _timer2_Elapsed(object sender, ElapsedEventArgs e)
{
WriteConsoleMessage(CountDownValue--);
if (CountDownValue == 0)
{
// Stop timer2
// Start timer1
}
}
private static void WriteConsoleMessage(int Value)
{
if (Value < COUNTDOWN_SECONDS)
Console.CursorLeft = 0; // Reset cursor to start of the line
Console.Write(string.Format("{0} Seconds until timer starts", Value.ToString());
}
Heres how i did it:
public static int Interval = 5000;
public static int IntervalLeft = Interval;
Timer.Elapsed += _timer_Elapsed;
Timer.Enabled = true;
Timer.Interval = Interval;
CountDownTimer.Elapsed += _CountDowntimer_Elapsed;
CountDownTimer.Enabled = true;
CountDownTimer.Interval = 1000;
CountDownTimer.Start();
private static void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
CountDownTimer.Stop();
Timer.Stop();
DOES THE JOB HERE
Timer.Start();
CountDownTimer.Start();
IntervalLeft = Interval;
}
private static void _CountDowntimer_Elapsed(object sender, ElapsedEventArgs e)
{
Zipper.ClearCurrentConsoleLine();
IntervalLeft = (IntervalLeft - 1000);
Console.Write("Starts in" + IntervalLeft/1000);
}
The first timer one stops the second timer when it elapses...

How to trigger an event every specific time interval in C#?

the timer needs to be run as a thread and it will trigger an event every fixed interval of time. How can we do it in c#?
Here's a short snippet that prints out a message every 10 seconds.
using System;
public class AClass
{
private System.Timers.Timer _timer;
private DateTime _startTime;
public void Start()
{
_startTime = DateTime.Now;
_timer = new System.Timers.Timer(1000*10); // 10 seconds
_timer.Elapsed += timer_Elapsed;
_timer.Enabled = true;
Console.WriteLine("Timer has started");
}
void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
TimeSpan timeSinceStart = DateTime.Now - _startTime;
string output = string.Format("{0},{1}\r\n", DateTime.Now.ToLongDateString(), (int) Math.Floor( timeSinceStart.TotalMinutes));
Console.Write(output);
}
}
Use one of the multiple timers available. Systme.Timer as a generic one, there are others dpending on UI technology:
System.Timers.Timer
System.Threading.Timer
System.Windows.Forms.Timer
System.Web.UI.Timer
System.Windows.Threading.DispatcherTimer
You can check Why there are 5 Versions of Timer Classes in .NET? for an explanation of the differences.
if you need something with mroore precision (down to 1ms) you an use the native timerqueues - but that requies some interop coding (or a very basic understanding of google).
I prefer using Microsoft's Reactive Framework (Rx-Main in NuGet).
var subscription =
Observable
.Interval(TimeSpan.FromSeconds(1.0))
.Subscribe(x =>
{
/* do something every second here */
});
And to stop the timer when not needed:
subscription.Dispose();
Super easy!
You can use System.Timers.Timer
Try This:
class Program
{
static System.Timers.Timer timer1 = new System.Timers.Timer();
static void Main(string[] args)
{
timer1.Interval = 1000;//one second
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
timer1.Start();
Console.WriteLine("Press \'q\' to quit the sample.");
while (Console.Read() != 'q') ;
}
static private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
//do whatever you want
Console.WriteLine("I'm Inside Timer Elapsed Event Handler!");
}
}

Timer Interval Calling Long Method

What would happen with the code below if Execute() takes, say, 3000ms to finish, but is being called every 1000ms due to the timer interval?
Timer _timer = new Timer();
private void setupTimer()
{
_timer.Tick += new EventHandler(pollingTimeElapsed);
_timer.Interval = 1000;
_timer.Enabled = true;
_timer.Start();
}
private void pollingTimeElapsed(object sender, EventArgs e)
{
Execute();
}
EDIT: I am using System.Windows.Forms.Timer, since System.Timers.Timer doesn't have .Tick
I'm assuming you are using the System.Timers.Timer class.
Since AutoReset has the default value (which is True), the Elapsed event will be fired for each time 1000ms has elapsed.
If you want to fire the event only one time, set AutoReset to False.
If you do not want to fire the event while your execute-code is running, do the following:
Timer _timer = new Timer();
private void setupTimer() {
_timer.Tick += new EventHandler(pollingTimeElapsed);
_timer.Interval = 1000;
_timer.Enabled = true;
_timer.Start();
}
private void pollingTimeElapsed(object sender, EventArgs e) {
try {
_timer.Stop()
Execute();
} finally {
_timer.Start()
}
}

Timer won't tick

I have a Windows.Forms.Timer in my code, that I am executing 3 times. However, the timer isn't calling the tick function at all.
private int count = 3;
private timer;
void Loopy(int times)
{
count = times;
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
count--;
if (count == 0) timer.Stop();
else
{
// Do something here
}
}
Loopy() is being called from other places in the code.
Try using System.Timers instead of Windows.Forms.Timer
void Loopy(int times)
{
count = times;
timer = new Timer(1000);
timer.Enabled = true;
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
throw new NotImplementedException();
}
If the method Loopy() is called in a thread that is not the main UI thread, then the timer won't tick.
If you want to call this method from anywhere in the code then you need to check the InvokeRequired property. So your code should look like (assuming that the code is in a form):
private void Loopy(int times)
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
Loopy(times);
});
}
else
{
count = times;
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
}
I am not sure what you are doing wrong it looks correct, This code works: See how it compares to yours.
public partial class Form1 : Form
{
private int count = 3;
private Timer timer;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Loopy(count);
}
void Loopy(int times)
{
count = times;
timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
count--;
if (count == 0) timer.Stop();
else
{
//
}
}
}
Here's an Rx ticker that works:
Observable.Interval(TimeSpan.FromSeconds(1))
.Take(3)
.Subscribe(x=>Console.WriteLine("tick"));
Of course, you can subscribe something more useful in your program.
you may have started the timer from another thread, so try invoking it from the correct thread.
for example, instead of:
timerX.start();
Use:
Invoke((MethodInvoker)delegate { timerX.Start(); });
Check if your timer in properties is enabled.
Mine was false and after setting to true it worked.
If you are using Windows.Forms.Timer then should use something like following.
//Declare Timer
private Timer _timer= new Timer();
void Loopy(int _time)
{
_timer.Interval = _time;
_timer.Enabled = true;
_timer.Tick += new EventHandler(timer_Elapsed);
_timer.Start();
}
void timer_Elapsed(object sender, EventArgs e)
{
//Do your stuffs here
}
If you use some delays smaller than the interval inside the timer, the system.timer will execute other thread and you have to deal with a double thread running at the same time. Apply an InvokeRequired to control the flow.

Categories