How to use same timer for different time intervals? - c#

I am using a timer in my code. Status bar updates in tick event on clicking respective button for the time inteval mentioned in properties say one second. Now i want to use the same timer for a different time interval say two seconds for a different oepration. How to achieve that?

Create a second timer. There is nothing to gain from hacking the first timer.
As #Henk noted, Timers are not that expensive. (Especially not compared to fixing hard to maintain code!)

I agree with #Henk and others.
But still, something like this could work:
Example
Int32 counter = 0;
private void timer1_Tick(object sender, EventArgs e)
{
if (counter % 1 == 0)
{
OnOneSecond();
}
if (counter % 2 == 0)
{
OnTwoSecond();
})
counter++;
}
Updated Example
private void Form_Load()
{
timer1.Interval = 1000; // 1 second
timer1.Start(); // This will raise Tick event after 1 second
OnTick(); // So, call Tick event explicitly when we start timer
}
Int32 counter = 0;
private void timer1_Tick(object sender, EventArgs e)
{
OnTick();
}
private void OnTick()
{
if (counter % 1 == 0)
{
OnOneSecond();
}
if (counter % 2 == 0)
{
OnTwoSecond();
}
counter++;
}

Change timer Interval property.

Change the Interval property in every elapsed time. for example, this program process data 30 seconds and sleep 10 seconds.
static class Program
{
private System.Timers.Timer _sleepTimer;
private bool _isSleeping = false;
private int _processTime;
private int _noProcessTime;
static void Main()
{
_processTime = 30000; //30 seconds
_noProcessTime = 10000; //10 seconds
this._sleepTimer = new System.Timers.Timer();
this._sleepTimer.Interval = _processTime;
this._sleepTimer.Elapsed += new System.Timers.ElapsedEventHandler(sleepTimer_Elapsed);
ProcessTimer();
this._sleepTimer.Start();
}
private void sleepTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
ProcessTimer();
}
private void ProcessTimer()
{
_sleepTimer.Enabled = false;
_isSleeping = !_isSleeping;
if (_isSleeping)
{
_sleepTimer.Interval = _processTime;
//process data HERE on new thread;
}
else
{
_sleepTimer.Interval = _noProcessTime;
//wait fired thread and sleep
Task.WaitAll(this.Tasks.ToArray());
}
_sleepTimer.Enabled = true;
}
}

Related

Measuring code execution while showing time elapsed every second in C#

I am wondering what is the best way to achieve this in Windows Forms - what I need is a window showing time elapsed (1 sec 2 secs etc) up to 90 seconds while code is being executed. I have a timer right now implemented as follows but I think I also need a stopwatch there as well since the Timer blocks the main thread.
static System.Timers.Timer pXRFTimer = new System.Timers.Timer();
static int _pXRFTimerCounter = 0;
private void ScanpXRF()
{
_pXRFTimerCounter = 0;
pXRFTimer.Enabled = true;
pXRFTimer.Interval = 1000;
pXRFTimer.Elapsed += new ElapsedEventHandler(pXRFTimer_Tick);
pXRFTimer.Start();
//START action to be measured here!
DoSomethingToBeMeasured();
}
private static void pXRFTimer_Tick(Object sender, EventArgs e)
{
_pXRFTimerCounter++;
if (_pXRFTimerCounter >= 90)
{
pXRFTimer.Stop();
}
else
{
//show time elapsed
}
}
I'm not sure about mechanics of your app, but time elapsed can be calculated with something like this
DateTime startUtc;
private void ScanpXRF()
{
startUtc = DateTime.NowUtc;
(...)
//START action to be measured here!
}
private static void pXRFTimer_Tick(Object sender, EventArgs e)
{
var elapsed = DateTime.NowUtc - startUtc;
var elapsedSeconds = elapsed.TotalSeconds; // double so you may want to round.
}

c# timer is going too fast if set

i'm trying to implement a simple countdown using Timer (using https://www.geoffstratton.com/cnet-countdown-timer code). it does work if i run the timer once but if i stop the timer or the timer goes to 00:00 the next time i'll start it, it will go 2x faster. if i stop it and start it again it will go 3x faster.
(my explaination may be not clear, i did a gif that demonstrate the problem)
https://media.giphy.com/media/fQr7sX6LNRECvQpCYP/giphy.gif
i'm very novice at c#, i usually figure things out but i cant get what's happening here.
I included the timer code. if somebody can help me with this it would be awesome!
Thanks !!!
private void btnStartTimer_Click(object sender, EventArgs e)
{
if (txtTimer.Text == "00:00")
{
MessageBox.Show("Please enter the time to start!", "Enter the Time", MessageBoxButtons.OK);
}
else
{
string[] totalSeconds = txtTimer.Text.Split(':');
int minutes = Convert.ToInt32(totalSeconds[0]);
int seconds = Convert.ToInt32(totalSeconds[1]);
timeLeft = (minutes * 60) + seconds;
btnStartTimer.Enabled = false;
btnCleartimer.Enabled = false;
txtTimer.ReadOnly = true;
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
}
private void btnStopTimer_Click(object sender, EventArgs e)
{
timer1.Stop();
timeLeft = 0;
btnStartTimer.Enabled = true;
btnCleartimer.Enabled = true;
txtTimer.ReadOnly = false;
}
private void btnCleartimer_Click(object sender, EventArgs e)
{
txtTimer.Text = "00:00";
}
private void timer1_Tick(object sender, EventArgs e)
{
if (timeLeft > 0)
{
timeLeft = timeLeft - 1;
// Display time remaining as mm:ss
var timespan = TimeSpan.FromSeconds(timeLeft);
txtTimer.Text = timespan.ToString(#"mm\:ss");
// Alternate method
//int secondsLeft = timeLeft % 60;
//int minutesLeft = timeLeft / 60;
}
else
{
timer1.Stop();
SystemSounds.Exclamation.Play();
MessageBox.Show("Time's up!", "Time has elapsed", MessageBoxButtons.OK);
}
}
You need to unsubscribe from the event in your btnStopTimer_Click method:
timer1.Tick -= timer1_Tick;
You are adding the event to Count every time you start the timer. As a result, the first time you call it there is only one event, the second time two events and so on. As a result, you first go down one second, then two,....
I would recommend creating the timer separately and just call Start and Stop.
Alternativ, user Dmitry Korolev answered a good Approach if you don't want to create the timer somewhere else
timer1.Tick -= timer1_Tick;

How I can stop a timer with seconds in real time c#?

I'm trying to stop a timer when 16 seconds in real time have passed, but i don't know how i can do that.
I made this little example: when picturebox1 intersects with picturebox2,this action activate a timer, and this timer have to shows the picturebox3 during 16 seconds in real time and after stop it(timer) (and the picturebox3 doesn't show).
(Sorry for my english. But StackOverflow in Spanish doesn't have many information).
I'm using windows form and C#
private void timer2_Tick(object sender, EventArgs e)
{
pictureBox7.Hide();
if ((pictureBox3.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible) || (pictureBox5.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible))
{
puntaje++;
this.Text = "Puntaje: " + puntaje;
if (puntaje % 5 == 0)
{
timer3.Enabled=true;
//This is the part where i want set down the timer3, timer 2 is on
}
}
You can try this, on your timer tick event handler. Timespan counts the elapsed time between two dates. On this case since its 16 seconds, we count it by negative.
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan ts = dtStart.Subtract(DateTime.Now);
if (ts.TotalSeconds <= -16)
{
timer1.Stop();
}
}
Make sure your dtStart (DateTime) is declared when you start your timer:
timer1.Start();
dtStart = DateTime.Now;
The cleanest way I can see this implemented is by using the interval parameter of a System.Timers.Timer.
Here's a sample snippet of the code
var timer = new Timer(TimeSpan.FromSeconds(16).TotalMilliseconds) { AutoReset = false };
timer.Elapsed += (sender, e) =>
{
Console.WriteLine($"Finished at exactly {timer.Interval} milliseconds");
};
_timer.Start();
The TimeSpan.FromSeconds(16).TotalMilliseconds basically converts to 16000 but I used the TimeSpan static method for you to understand it easier and looks more readable.
The AutoReset property of the timer tells it that it should only be triggered once.
Adjusted for your code
private void timer2_Tick(object sender, EventArgs e)
{
pictureBox7.Hide();
if ((pictureBox3.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible)
|| (pictureBox5.Bounds.IntersectsWith(pictureBox2.Bounds) && pictureBox2.Visible))
{
puntaje++;
this.Text = "Puntaje: " + puntaje;
if (puntaje % 5 == 0)
{
var timer3 = new Timer(TimeSpan.FromSeconds(16).TotalMilliseconds) { AutoReset = false };
timer3.Elapsed += (sender, e) =>
{
pictureBox3.Visible = true;
};
timer3.Start();
}
}
}
Please do mark the question Answered if this solves your issue.

How to set timer to execute at specific time in c#

I have a requirement where i need to execute timer at 00:01:00 A.M every day...But i am not getting how to achieve this ..If i am taking Systems time,it can be in different format..
Here is my timer code..
static System.Timers.Timer timer;
timer = new System.Timers.Timer();
timer.Interval = 1000 * 60 * 60 * 24;//set interval of one day
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
start_timer();
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
// Add timer code here
}
private static void start_timer()
{
timer.Start();
}
If you want to start a timer at exactly 00:01:00am do some processing time and then restart the timer you just need to calculate the difference between Now and the next 00:01:00am time slot such as.
static Timer timer;
static void Main(string[] args)
{
setup_Timer();
}
static void setup_Timer()
{
DateTime nowTime = DateTime.Now;
DateTime oneAmTime = new DateTime(nowTime.Year, nowTime.Month, nowTime.Day, 0, 1, 0, 0);
if (nowTime > oneAmTime)
oneAmTime = oneAmTime.AddDays(1);
double tickTime = (oneAmTime - nowTime).TotalMilliseconds;
timer = new Timer(tickTime);
timer.Elapsed += timer_Elapsed;
timer.Start();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
timer.Stop();
//process code..
setup_Timer();
}
What you should do is write your program that does whatever you need it to do, and then use your OS's built-in task scheduler to fire it off. That'd be the most reliable. Windows's Task Scheduler, for instance, can start your app before the user logs in, handle restarting the app if necessary, log errors and send notifications, etc.
Otherwise, you'll have to run your app 24/7, and have it poll for the time at regular intervals.
For instance, you could change the interval every minute:
timer.Interval = 1000 * 60;
And inside your Elapsed event, check the current time:
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (DateTime.Now.Hour == 1 && DateTime.Now.Minute == 0)
{
// do whatever
}
}
But this is really unreliable. Your app may crash. And dealing with DateTime's can be tricky.
You could always calculate it:
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
// Do stuff
start_timer();
}
private static void start_timer()
{
timer.Interval = CalculateInterval();
timer.Start();
}
private static double CalculateInterval()
{
// 1 AM the next day
return (DateTime.Now.AddDays(1).Date.AddHours(1) - DateTime.Now).TotalMilliseconds;
}
Here is a timer implementation which takes an Interval (just like any other timer) and fires exactly when that interval expires, even the machine goes to sleep mode in between.
public delegate void TimerCallbackDelegate(object sender, ElapsedEventArgs e);
public class TimerAbsolute : System.Timers.Timer
{
private DateTime m_dueTime;
private TimerCallbackDelegate callback;
public TimerAbsolute(TimerCallbackDelegate cb) : base()
{
if (cb == null)
{
throw new Exception("Call back is NULL");
}
callback = cb;
this.Elapsed += this.ElapsedAction;
this.AutoReset = true;
}
protected new void Dispose()
{
this.Elapsed -= this.ElapsedAction;
base.Dispose();
}
public double TimeLeft
{
get
{
return (this.m_dueTime - DateTime.Now).TotalMilliseconds;
}
}
public int TimeLeftSeconds
{
get
{
return (int)(this.m_dueTime - DateTime.Now).TotalSeconds;
}
}
public void Start(double interval)
{
if (interval < 10)
{
throw new Exception($"Interval ({interval}) is too small");
}
DateTime dueTime = DateTime.Now.AddMilliseconds(interval);
if (dueTime <= DateTime.Now)
{
throw new Exception($"Due time ({dueTime}) should be in future. Interval ({interval})");
}
this.m_dueTime = dueTime;
// Timer tick is 1 second
this.Interval = 1 * 1000;
base.Start();
}
private void ElapsedAction(object sender, System.Timers.ElapsedEventArgs e)
{
if (DateTime.Now >= m_dueTime)
{
// This means Timer expired
callback(sender, e);
base.Stop();
}
}
}

C# timer stop after some number of ticks automatically

How to stop a timer after some numbers of ticks or after, let's say, 3-4 seconds?
So I start a timer and I want after 10 ticks or after 2-3 seconds to stop automatically.
Thanks!
You can keep a counter like
int counter = 0;
then in every tick you increment it. After your limit you can stop timer then. Do this in your tick event
counter++;
if(counter ==10) //or whatever your limit is
yourtimer.Stop();
When the timer's specified interval is reached (after 3 seconds), timer1_Tick() event handler will be called and you could stop the timer within the event handler.
Timer timer1 = new Timer();
timer1.Interval = 3000;
timer1.Enabled = true;
timer1.Tick += new System.EventHandler(timer1_Tick);
void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop(); // or timer1.Enabled = false;
}
i generally talking because you didn't mention which timer, but they all have ticks... so:
you'll need a counter in the class like
int count;
which you'll initialize in the start of your timer, and you'll need a dateTime like
DateTime start;
which you'll initialize in the start of your timer:
start = DateTime.Now;
and in your tick method you'll do:
if(count++ == 10 || (DateTime.Now - start).TotalSeconds > 2)
timer.stop()
here is a full example
public partial class meClass : Form
{
private System.Windows.Forms.Timer t;
private int count;
private DateTime start;
public meClass()
{
t = new Timer();
t.Interval = 50;
t.Tick += new EventHandler(t_Tick);
count = 0;
start = DateTime.Now;
t.Start();
}
void t_Tick(object sender, EventArgs e)
{
if (count++ >= 10 || (DateTime.Now - start).TotalSeconds > 10)
{
t.Stop();
}
// do your stuff
}
}
Assuming you are using the System.Windows.Forms.Tick. You can keep track of a counter, and the time it lives like so. Its a nice way to use the Tag property of a timer.
This makes it reusable for other timers and keeps your code generic, instead of using a globally defined int counter for each timer.
this code is quiet generic as you can assign this event handler to manage the time it lives, and another event handler to handle the specific actions the timer was created for.
System.Windows.Forms.Timer ExampleTimer = new System.Windows.Forms.Timer();
ExampleTimer.Tag = new CustomTimerStruct
{
Counter = 0,
StartDateTime = DateTime.Now,
MaximumSecondsToLive = 10,
MaximumTicksToLive = 4
};
//Note the order of assigning the handlers. As this is the order they are executed.
ExampleTimer.Tick += Generic_Tick;
ExampleTimer.Tick += Work_Tick;
ExampleTimer.Interval = 1;
ExampleTimer.Start();
public struct CustomTimerStruct
{
public uint Counter;
public DateTime StartDateTime;
public uint MaximumSecondsToLive;
public uint MaximumTicksToLive;
}
void Generic_Tick(object sender, EventArgs e)
{
System.Windows.Forms.Timer thisTimer = sender as System.Windows.Forms.Timer;
CustomTimerStruct TimerInfo = (CustomTimerStruct)thisTimer.Tag;
TimerInfo.Counter++;
//Stop the timer based on its number of ticks
if (TimerInfo.Counter > TimerInfo.MaximumTicksToLive) thisTimer.Stop();
//Stops the timer based on the time its alive
if (DateTime.Now.Subtract(TimerInfo.StartDateTime).TotalSeconds > TimerInfo.MaximumSecondsToLive) thisTimer.Stop();
}
void Work_Tick(object sender, EventArgs e)
{
//Do work specifically for this timer
}
When initializing your timer set a tag value to 0 (zero).
tmrAutoStop.Tag = 0;
Then, with every tick add one...
tmrAutoStop.Tag = int.Parse(tmrAutoStop.Tag.ToString()) + 1;
and check if it reached your desired number:
if (int.Parse(tmrAutoStop.Tag.ToString()) >= 10)
{
//do timer cleanup
}
Use this same technique to alternate the timer associated event:
if (int.Parse(tmrAutoStop.Tag.ToString()) % 2 == 0)
{
//do something...
}
else
{
//do something else...
}
To check elapsed time (in seconds):
int m = int.Parse(tmrAutoStop.Tag.ToString()) * (1000 / tmrAutoStop.Interval);

Categories

Resources