How to Increment timer asynchronously ? - c#

I am trying to Update a timer asynchronously On a Button Click .
say example i have set the time = 60 seconds
and when i run the program after few TIME the timer has reached to 45 seconds and when i click the Button ,then it should add j=15 seconds to the time and the timer should change to 60 seconds asynchronously. Please Help
private int time = 60;
DateTime dt = new DateTime();
private j = 15 ;
private DispatcherTimer timer;
public MainWindow()
{
InitializeComponent();
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1);
timer.Tick += timer_tick;
timer.Start();
}
void timer_tick(object sender, EventArgs e)
{
if (time >0)
{
time--;
text.Text = TimeSpan.FromSeconds(time).ToString();
}
else
{
timer.Stop();
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
text.Text = dt.AddSeconds(j).ToString("HH:mm:ss");
}

Here is my code you can try it it's working.
private int time = 60;
DateTime dt = new DateTime();
private int j = 15;
private Timer timer1 = new Timer();
void timer_tick(object sender, EventArgs e)
{
if (time > 0)
{
time--;
text.Text = TimeSpan.FromSeconds(time).ToString();
}
else
{
timer1.Stop();
}
}
public timer()
{
InitializeComponent();
timer1 = new Timer();
timer1.Interval = 1000;
timer1.Tick += timer_tick;
timer1.Start();
}
private void button1_Click(object sender, EventArgs e)
{
time += j;
}

Related

Countdown from 30 seconds to 0 seconds, showing 2 decimals in the last second with Xamarin.Forms c#

I am very new to Xamarin. What I want to make is a shot clock. It needs to countdown from 30 seconds to 0 seconds, and in the last second it needs to show 2 decimals. I also need it to Pause when I click BtnPause, and if I click the BtnStart I want it to restart at the exact moment I paused it, so the countdown has to be paused and started with the timer paused, not reset.
This is my code, excuse my mistakes and bad programming skills.
public partial class MainPage : ContentPage
{
private static System.Timers.Timer _timer;
private double _shotClock = 30;
public MainPage()
{
InitializeComponent();
_timer = new Timer();
}
private void BtnStart_Clicked(object sender, EventArgs e)
{
RunTimer();
}
private void BtnPause_Clicked(object sender, EventArgs e)
{
PauseTimer();
}
private void RunTimer()
{
if (_shotClock < 1.00)
{
_timer.Interval = 10;
}
else
{
_timer.Interval = 1000;
}
_timer.Start();
_timer.Elapsed += OnTimedEvent;
}
private void PauseTimer()
{
_timer.Stop();
}
private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
Device.BeginInvokeOnMainThread(() => {
if (_shotClock > 1.00)
{
_shotClock -= 1.00;
_shotClock = Math.Round(_shotClock, 2);
lblTimer.Text = _shotClock.ToString();
}
else if (_shotClock <= 1.00 && _shotClock > 0.00)
{
_shotClock -= 0.01;
_timer.Interval = 10;
_shotClock = Math.Round(_shotClock, 2);
lblTimer.Text = _shotClock.ToString();
}
else
{
lblTimer.Text = "0";
_timer.Stop();
}
});
}
}
What is going wrong:
I do not believe it counts exact seconds, especially when I envoke Runtimer() the first few seconds are off and I'm not sure one countdown is one second. And when I envoke Pausetimer() and then Runtimer() one second gets skipped.
Is there a better way to code this?
Haven't compiled this, so I'm not sure if it will work without some tweaking, but I hope you get the idea. Basically, you'll have to calculate the elapsed time manually. The seconds being off in your case was probably because of using Round() instead of Floor()
public partial class MainPage : ContentPage
{
private static System.Timers.Timer _timer;
private double _shotClock = 30;
private DateTime _startTime;
public MainPage()
{
InitializeComponent();
_timer = new Timer();
_timer.Interval = 10;
_timer.Elapsed += OnTimedEvent;
}
private void BtnStart_Clicked(object sender, EventArgs e)
{
_startTime = DateTime.UtcNow;
_timer.Start();
}
private void BtnPause_Clicked(object sender, EventArgs e)
{
_shotClock -= (DateTime.UtcNow - _startTime).TotalSeconds;
_shotClock = Math.Floor(_shotClock);
_timer.Stop();
}
private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
Device.BeginInvokeOnMainThread(() => {
var elapsedSinceBtnStartPressed = (DateTime.UtcNow - _startTime).TotalSeconds;
var remaining = _shotClock - elapsedSinceBtnStartPressed;
if (remaining > 1.00)
{
lblTimer.Text = Math.Floor(remaining).ToString();
}
else if (remaining <= 1.00 && remaining > 0.00)
{
lblTimer.Text = Math.Round(remaining, 2).ToString();
}
else
{
lblTimer.Text = "0";
_timer.Stop();
}
});
}
}
You might also want to try Math.Ceiling() instead of Math.Floor() if you want 12.53 displayed as 13 instead of 12.
with the help of the accepted answer I got the basics working:
public partial class MainPage : ContentPage
{
private static System.Timers.Timer _timer;
private double _shotClock;
private DateTime _startTime;
public MainPage()
{
InitializeComponent();
_timer = new Timer();
_timer.Interval = 10;
_timer.Elapsed += OnTimedEvent;
_shotClock = 30.00;
}
private void BtnStart_Clicked(object sender, EventArgs e)
{
_startTime = DateTime.UtcNow;
_timer.Start();
}
private void BtnPause_Clicked(object sender, EventArgs e)
{
_timer.Stop();
var elapsedSinceBtnPausePressed = (DateTime.UtcNow - _startTime).TotalSeconds;
_shotClock -= elapsedSinceBtnPausePressed;
}
private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
var elapsedSinceBtnStartPressed = (DateTime.UtcNow - _startTime).TotalSeconds;
var remaining = _shotClock - elapsedSinceBtnStartPressed;
Device.BeginInvokeOnMainThread(() => {
if (remaining > 1.00)
{
lblTimer.Text = Math.Floor(remaining).ToString();
}
else if (remaining <= 1.00 && remaining > 0.00)
{
lblTimer.Text = Math.Round(remaining, 2).ToString();
}
else
{
lblTimer.Text = "0";
_timer.Stop();
}
});
}
}

Timer firing every second and updating GUI (C# Windows Forms)

I have a Windows Forms application where I need to have a timer working for 90 seconds and every second should be shown after it elapses, kind of like a stopwatch 1..2..3 etc, after 90 seconds is up, it should throw an exception that something is wrong.
I have the following code, but the RunEvent never fires.
private void ScanpXRF()
{
bool demo = false;
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
try
{
for (int timerCounter = 0; timerCounter < 90; timerCounter++)
{
timer.Interval = 1000;
timer.Tick += new EventHandler(RunEvent);
timer.Start();
if(timerCounter == 89) {
throw new Exception();
}
}
}
catch (Exception e)
{
timer.Dispose();
MessageBox.Show("There is a problem!");
}
}
private void RunEvent(object sender, System.EventArgs e)
{
//boxStatus.AppendText("RunEvent() called at " + DateTime.Now.ToLongTimeString() + "\n");
MessageBox.Show("timer fired!");
}
Is there anything I am doing wrong here or are there other suggestions for other ways to achieve the same result?
A timer needs to be declared at the form level, or else it may not be disposed of when the form closes:
System.Windows.Forms.Timer timer;
int counter = 0;
Your starting code should just start the timer:
private void ScanpXRF()
{
counter = 0;
timer = new System.Windows.Forms.Timer();
timer.Interval = 1000;
timer.Tick += RunEvent;
timer.Start();
}
The RunEvent is your Tick event being called every second, so your logic needs to go in there:
private void RunEvent(object sender, EventArgs e)
{
counter++;
if (counter >= 90) {
timer.Stop();
// do something...
}
}
made it work
private void ScanpXRF()
{
_pXRFTimerCounter = 0;
pXRFTimer.Enabled = true;
pXRFTimer.Interval = 1000;
pXRFTimer.Elapsed += new ElapsedEventHandler(pXRFTimer_Tick);
pXRFTimer.Start();
}
private static void pXRFTimer_Tick(Object sender, EventArgs e)
{
_pXRFTimerCounter++;
if (_pXRFTimerCounter >= 90)
{
pXRFTimer.Stop();
// do something...
}
else
{
MessageBox.Show(_pXRFTimerCounter.ToString() + " seconds passed");
}
}
I made the timer
System.Timers

Timer Countdown with progress bar C#

I want to sync my progress bar in my project with the timer countdown.
This is what I has now:
namespace Timer1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int counter=80;
DateTime dt = new DateTime();
private void button1_Click(object sender, EventArgs e)
{
int counter = 80;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
textBox1.Text = counter.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
progressBar1.Increment(1);
if (counter == 0)
{
timer1.Stop();
}
textBox1.Text = dt.AddSeconds(counter).ToString("mm:ss");
}
private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = false;
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
textBox1.Clear();
progressBar1.Value = 0;
}
}
}
I want the progress bar to finish when the timer to ends.
You need to specify the progressBar1 to have its .Step and Maximum properties match the Interval and counter variable. For example:
private int counter = 80;
DateTime dt = new DateTime();
private void button1_Click(object sender, EventArgs e)
{
// The max is the total number of iterations on the
// timer tick by the number interval.
progressBar1.Max = counter * 1000;
progressBar1.Step = 1000;
timer1 = new System.Windows.Forms.Timer();
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Interval = 1000;
timer1.Start();
textBox1.Text = counter.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
counter--;
// Perform one step...
progressBar1.PerformStep();
if (counter == 0)
{
timer1.Stop();
}
textBox1.Text = dt.AddSeconds(counter).ToString("mm:ss");
}

auto refresh windows form in specific time c#

Hello I do this code for does this statement ( MessageBox.Show("done ");) when the time is between 11:47 , 11:49
public Form1()
{
InitializeComponent();
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (1 * 60 *500 ); // 1 mins
MyTimer.Tick += new EventHandler(times);
MyTimer.Start();
}
private void times(object sender, EventArgs e)
{
DateTime t1 = DateTime.Parse("11:47:00.000");
DateTime t2 = DateTime.Parse("11:49:00.000");
TimeSpan now = DateTime.UtcNow.TimeOfDay;
if (t1.TimeOfDay <= now && t2.TimeOfDay >= now)
{
MessageBox.Show("done ");
}
but it doesn't working
You created DateTime and Timespan, where DateTime is a point in time and TimeSpan is an interval between two points in time.
Also a second has 1000 milliseconds, so better use:
MyTimer.Interval = (1 * 60 * 1000); // 1 mins
Try this:
public Form1()
{
InitializeComponent();
System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (1 * 60 * 1000); // 1 mins
MyTimer.Tick += new EventHandler(times);
MyTimer.Start();
}
private void times(object sender, EventArgs e)
{
DateTime t1 = DateTime.Parse("11:47:00.000");
DateTime t2 = DateTime.Parse("11:50:00.000");
DateTime now = DateTime.Now;
if (t1 <= now && t2 >= now)
{
MessageBox.Show("done ");
}
}
Here's how to make it trigger at 11:48...
private System.Windows.Forms.Timer MyTimer;
private TimeSpan TargetTime = new TimeSpan(11, 48, 0);
public Form1()
{
InitializeComponent();
MyTimer = new System.Windows.Forms.Timer();
MyTimer.Interval = (int)MillisecondsToTargetTime(TargetTime);
MyTimer.Tick += new EventHandler(times);
MyTimer.Start();
}
private double MillisecondsToTargetTime(TimeSpan ts)
{
DateTime dt = DateTime.Today.Add(ts);
if (DateTime.Now > dt)
{
dt = dt.AddDays(1);
}
return dt.Subtract(DateTime.Now).TotalMilliseconds;
}
private void times(object sender, EventArgs e)
{
MyTimer.Stop();
MessageBox.Show("It's " + TargetTime.ToString(#"hh\:mm"));
MyTimer.Interval = (int)MillisecondsToTargetTime(TargetTime);
MyTimer.Start();
}

1 minute countdown timer

I am trying to do a simple countdown timer from 1 minute, that is shown in the button text. When the button is pressed I just want it to count down to 0, the show "times up". I have been reading all the posts I can find trying to figure out how to do this and cannot. Can someone tell me what I am doing wrong.
This is in in visual c# windows phone application. I hope I made the post appear correctly, this is my first time to ask a question on this site, I am new to this. Thank you in advance for any advice.
void bTime_Click(object sender, RoutedEventArgs e)
{
DispatcherTimer timer1 = new DispatcherTimer();
timer1.Interval = TimeSpan.FromSeconds(60);
timer1.Tick += new EventHandler(timer_Tick);
timer1.Start();
}
int tik = 60;
void timer_Tick(object sender, EventArgs e)
{
bTime.Content = timer.ToString();
if (tik > 0)
Countdown.Text = (timer--).ToString();
else
Countdown.Text = "Times Up";
throw new NotImplementedException();
}
First, get rid of throw new NotImplementedException. Second, you need to decrement tik. So something like this:
DispatcherTimer timer1 = new DispatcherTimer();
private void button1_Click(object sender, RoutedEventArgs e)
{
timer1.Interval = new TimeSpan(0, 0, 0, 1);
timer1.Tick += new EventHandler(timer1_Tick);
timer1.Start();
}
int tik = 60;
void timer1_Tick(object sender, EventArgs e)
{
Countdown.Text = tik + " Seconds Remaining";
if (tik > 0)
tik--;
else
Countdown.Text = "Times Up";
}
I have changed Interval and i'm decrementing tik every second. Nice and simple. Hope it helps. Let me know if you don't understand.
What is wrong with your code? To me it looks like these parts:
bTime.Content = timer.ToString();
and
bTime.Content = timer.ToString();
First of all, I don't even know what the variable timer is. Is it supposed to be timer1?
tik is never getting subtracted from and will always stay at 60.
Why don't you change your code to this:
DispatcherTimer timer1 = new DispatcherTimer();
void bTime_Click(object sender, RoutedEventArgs e)
{
timer1.Interval = TimeSpan.FromSeconds(60);
timer1.Tick += new EventHandler(timer_Tick);
timer1.Start();
}
int tik = 60;
void timer_Tick(object sender, EventArgs e)
{
bTime.Content = tik.ToString();
if (tik > 0)
Countdown.Text = (tik--).ToString();
else
{
Countdown.Text = "Times Up";
timer1.Stop();
}
throw new NotImplementedException();
}

Categories

Resources