C# Countdown Timer Then Do Something - c#

Looked everywhere, but everywhere i look theres a different way to do a countdown timer. Finally found some simple code. How do I make it do something when the time is complete.
This part is next to InitializeComponent();
timerlabel1.Text = TimeSpan.FromMinutes(720).ToString();
private void countdownTimer()
{
var startTime = DateTime.Now;
var timer = new Timer() { Interval = 1000 };
timer.Tick += (obj, args) =>
timerlabel1.Text =
(TimeSpan.FromMinutes(720) - (DateTime.Now - startTime))
.ToString("hh\\:mm\\:ss");
timer.Enabled = true;
}
This is where i need help, how do i make it do something when the time is done. I tried if timer.Enabled =false; Do This. Cant figure it out.

Solution : you can assign the total seconds [TotalMinutes*60] into some variable and decrement each time the Timer Tick event raises.
if the totalseconds value becomes zero then stop the timer by calling timer.Stop() method.
Try This:
public int tootalsecs = 720 * 60;
private void countdownTimer()
{
var startTime = DateTime.Now;
var timer = new Timer() { Interval = 1000 };
timer.Tick += (obj, args) =>
{
if (tootalsecs==0)
{
timer.Stop();
}
else
{
timerlabel1.Text =
(TimeSpan.FromMinutes(720) - (DateTime.Now - startTime))
.ToString("hh\\:mm\\:ss");
tootalsecs--;
}
};
timer.Start();
}

try this may work for you
var timer=new Timer();
timer.Interval=1000;
timer.tick += timer_Tick;
timer.Start();
int i=0;
void timer_Tick(object sender, EventArgs e)
{
if(i<TimeSpan.FromMinutes(720))
{
timerlabel1.Text =
(TimeSpan.FromMinutes(720) - (DateTime.Now - startTime))
.ToString("hh\\:mm\\:ss");
}
else
{
timer.Stop();
/* do other work Here */
}
i++;
}
Try with this may work for you.

As there are couple Timer classes available (System.Windows.Forms.Timer, System.Threading.Timer and System.Timers.Timer) I will advice you to go with System.Timers.Timer.
It provides Elapsed event, instead of Tick event. That's what you're looking for.
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;

You can try to do as below.
Initialize in global scope.
var target;
timerlabel1.Text =target= DateTime.Now.Add(TimeSpan.FromMinutes(720));
Add a Timer and in timer1_Tick write the below code
var span = targetTime - DateTime.Now;
if (span.TotalSeconds > 0)
{
//it will continue till the time ends.
var temp = span.ToString();
temp=temp.Substring(0, 8);
timerlabel1.Text = temp;
}
else
//do your work here
Don't forget to validate the answer or mark as answer if it close to your need

Related

C# - Win Form stopping Timer tick

This is my implementation of a Win Form app that has a countdown timer:
readonly DateTime myThreshold;
public Form1()
{
InitializeComponent();
myThreshold = Utils.GetDate();
Timer timer = new Timer();
timer.Interval = 1000; //1 second
timer.Tick += new EventHandler(t_Tick);
timer.Start();
//Threshold check - this only fires once insted of each second
if (DateTime.Now.CompareTo(myThreshold) > 0)
{
// STOP THE TIMER
timer.Stop();
}
else
{
//do other stuff
}
}
void t_Tick(object sender, EventArgs e)
{
TimeSpan timeSpan = myThreshold.Subtract(DateTime.Now);
this.labelTimer.Text = timeSpan.ToString("d' Countdown - 'hh':'mm':'ss''");
}
The wanted behavior is to stop the timer and the tick function when the threshold is reached.
This now does not happens because the check is only executed once since it is placed in the Form1 initialization.
Does exist a way to add this check in a way to immediately stop the Timer once a condition has been meet?
If we define timer as a class field (so it can be accessed from all methods in the class), then we can just add the check to the Tick event itself, and stop the timer from there:
private Timer timer = new Timer();
void t_Tick(object sender, EventArgs e)
{
// Stop the timer if we've reached the threshold
if (DateTime.Now > myThreshold) timer.Stop();
TimeSpan timeSpan = myThreshold.Subtract(DateTime.Now);
this.labelTimer.Text = timeSpan.ToString("d' Countdown - 'hh':'mm':'ss''");
}

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.

Timer Implementation not Running every 5 seconds as intended c#

I have the following timer implementation. But the timer is not running every 5 seconds as needed. How can make this run every 5 seconds. At present its running about once in 30 seconds.
private void button1_Click(object sender, RoutedEventArgs e)
{
msgsent = 0;
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(0, 0, 5);
bool isenable = timer.IsEnabled;
timer.Start();
}
private async void timer_Tick(object sender, object e)
{
if (geo == null)
{
geo = new Geolocator();
}
Geoposition posi = await geo.GetGeopositionAsync();
if (posi.Coordinate.Point.Position.Latitude <= 12.9227 && posi.Coordinate.Point.Position.Longitude >= 080.1320)
{
if (msgsent <=1)
{
msgsent = msgsent + 1;
ShowDialog(new MessageDialog("Your Bus has crossed xyz"));
}
}
}
I'll give you a hint. If you understand where each goes, then it should be clear. If not, you will once you get better.
// in the class definition
int msgsent;
Timer timer;
and
// in the constructor
timer = new Timer();
timer.Tick += timer_Tick;
timer.Interval = new TimeSpan(0, 0, 5);
and
// in the Button.Click event handler
timer.Start();
and
// in the Timer.Tick event handler
timer.Stop();
/* do your work here */
timer.Start();
There will be further issues when the user is clicking the button while you're doing your work, but that's beyond the scope of this question.

How do I set the contents of a label and have it reset to string.empty after a period of 5 seconds in c# winforms?

I've no real idea how to do this and I have tried messing with a timer but to no avail so far.
So what am I trying to do?
I have a label that is blank. When a certain event is triggered I want the label to say "Competition successfully setup" for a period of 5 seconds after which I want it to return to being blank.
Surely this can be done?? Can it? I have played around with a timer but I seem to be well off the mark.
Any help would be most welcome. My feeble attempt is below.
private void UpdateLabel(object sender, EventArgs e)
{
var timer = new Timer()
{
Interval = 5000,
};
timer.Tick += (s, evt) =>
lblCompetitionSetupSuccess.Text = "Competition successfully setup";
timer.Start();
lblCompetitionSetupSuccess.Text = string.Empty;
}
Try the other way around:
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "I will vanish in 5 sec";
var timer = new Timer();
timer.Interval = 5000;
timer.Tick += (o, args) => label1.Text = "";
timer.Start();
}
First set the label to whatever text you want it to display for 5 sec
label1.Text = "I will vanish in 5 sec";
Then setup your timer so that on timer elapsed it will remove the text
var timer = new Timer();
timer.Interval = 5000;
timer.Tick += (o, args) => label1.Text = "";
timer.Start();
If you want the timer to stop after the first timer elapse:
timer.Tick += (o, args) =>
{
label1.Text = "";
timer.Enabled = false;
};
Make sure you're using the System.Windows.Forms.Timer class, which calls the tick event on the UI thread.

Timer is firing before the elapsed Interval

I'm trying to create a Windows Form application that searches for a string and has three possible scenarios:
String 1 found - wait
String 2 found - stop
Else - Perform action and wait 1 minute
I am encountering my problem only on the times when it is expected to wait. When this happens, the newTimer_Tick starts to tick every second. I have tried disabling the timer when it ticks and a few other things but none appeared to work. Below is the code:
public void Action(string result)
{
if (result.Contains("string1"))
{
// Check again in 10 + x seconds
int n = new Random().Next(0, 5000);
int newtime = 10000 + n;
newTimer.Tick += new EventHandler(newTimer_Tick);
newTimer.Interval = newtime;
newTimer.Enabled = true;
}
else if (result.Contains("string2"))
{
// Turn off
newTimer.Enabled = false;
}
else
{
// Perform action and tick again in 1min + x seconds
action1();
int n = new Random().Next(0, 5000);
int newtime = 600000 + n;
newTimer.Tick += new EventHandler(newTimer_Tick);
newTimer.Interval = newtime;
newTimer.Enabled = true;
}
}
private void newTimer_Tick(object sender, EventArgs e)
{
Action( result );
}
What have I done wrong?
Each time the following line is called, an new instance of the event handler newTimerTick is added to the invocation list for the Tick event:
newTimer.Tick += new System.EventHandler(newTimer_Tick);
So every time the time tick goes off newTimerTick is going to be called multiple times, which is going to give you unexpected results.
Configure your event handler once only. In the constructor would be a sensible place.
Have you tried to stop the timer with the Timer.Stop method?
Btw: I don't think you need to reassign the Tick event from the newTimer unless you don't create a new Timer everytime.
I think what you were missing is that you have to stop your timer since you don't actually want it to keep for more than one interval. You seem to want to run it once, check on the result and then decide if you want to keep running it or not. Here's the code:
public void action(string result)
{
int n = new Random().Next(0, 5000);
Boolean blActivateTimer = true;
Timer timer = new Timer();
timer.Tick += timer_Tick;
if (!result.Contains("string1") && !result.Contains("string2"))
{
n += 600000;
action1();
}
else
{
if (result.Contains("string1"))
{
n += 10000;
}
else
{
blActivateTimer = false;
}
}
if (blActivateTimer)
{
timer.Start();
}
}
void action1()
{
}
void timer_Tick(object sender, EventArgs e)
{
Timer t = (Timer)sender;
t.Stop();
action(result);
}

Categories