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();
}
Related
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();
}
});
}
}
I am using MvvmLight to develope WPF Application.I want to enabled button when 4 minute is remaining with the settled time.It should automatically enabled in UI.Should I use thread to continuously track difference of CurrentUTCtime and mytime ?If yes ,then How to use thread with this code ? Here is my code.
Datetime mytime = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,22,0,0)
public RelayCommand Open
{
get
{
return Open?? (_open= new RelayCommand(ExecuteOpen, CanExecuteOpen));
}
private void ExecuteOpen()
{
_navigation.NavigationToSetBetsDialogue();
}
private bool CanExecuteOpen()
{
double? remainingMinutes = null;
DateTime CurrentUTCtime = DateTime.UtcNow;
remainingMinutes = mytime .Subtract(CurrentUTCtime).TotalMinutes;
if (remainingMinutes <= 4)
{
return true;
}
else
{
return false;
}
}
}
Try using a DispatcherTimer:
private DispatcherTimer _Timer = new DispatcherTimer();
private bool _CanExecute;
private void StartTimer()
{
var mytime = new DateTime( DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 22, 0, 0 );
var interval = DateTime.UtcNow - mytime - TimeSpan.FromMinutes( 4 );
_Timer.Interval = interval;
_Timer.Tick += Timer_Tick;
}
private void Timer_Tick( object sender, EventArgs e )
{
_Timer.Tick -= Timer_Tick;
_CanExecute = true;
CommandManager.InvalidateRequerySuggested();
}
public ICommand Open
{
get { return new RelayCommand( ExecuteOpen, () => _CanExecute ); }
}
well you can use can execute and check for elapsed time no need for separate thread as can execute will run on parallel anyway...
private DateTime _startTime;
private void StartCommandHandler(object obj)
{
_startTime = DateTime.Now;
}
private bool CanEnableButton(object arg)
{
return _startTime != DateTime.MinValue && DateTime.Now.Subtract(_startTime).Minutes >= 4;
}
Hope it helps
You can do this with BackgroundWorker. First you need to inititalize worker:
BackgroundWorker bgWrkr = new BackgroundWorker();
bgWrkr.DoWork += new DoWorkEventHandler(bgWrkrDoWork);
bgWrkr.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWrkrRunWorkerCompleted);
Then implement handlers for events. DoWork:
void bgWrkrDoWork(object sender, DoWorkEventArgs e)
{
while (mytime.Subtract(DateTime.UtcNow).TotalMinutes >= 4){ }
}
and RunWorkerCompleted:
void bgWrkrRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
button.IsEnabled = true;
}
And sure you have to start worker:
bgWrkr.RunWorkerAsync();
You can start it right after initializing.bgWrkr.RunWorkerAsync();
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;
}
I am using below code to display time left in hh:mm:ss format for example if duration is 30min, it will show like this 00:30:00 and after 1 min it will show 00:29:00, how can i also display the remaining seconds and decrease them accordingly.,
Edit
I tried timer1.Interval = 1000; and
examTime = examTime.Subtract(TimeSpan.FromSeconds(1));
But its not showing me seconds reducing each second, How do i do it ?
public SubjectExamStart()
{
InitializeComponent();
examTime = TimeSpan.FromMinutes(double.Parse(conf[1]));
label1.Text = examTime.ToString();
timer1.Interval = 60 * 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (sender == timer1)
{
if (examTime.TotalMinutes > 0)
{
examTime = examTime.Subtract(TimeSpan.FromMinutes(1));
label1.Text = examTime.ToString();
}
else
{
timer1.Stop();
MessageBox.Show("Exam Time is Finished");
}
}
}
Instead of Subtracting TimeSpan.FromMinutes you need to subtract from TimeSpan.FromSeconds
public SubjectExamStart()
{
InitializeComponent();
examTime = TimeSpan.FromSeconds(double.Parse(conf[1]));
label1.Text = examTime.ToString();
timer1.Interval = 1000;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (sender == timer1)
{
if (examTime.TotalMinutes > 0)
{
examTime = examTime.Subtract(TimeSpan.FromSeconds(1));
label1.Text = examTime.ToString();
}
else
{
timer1.Stop();
MessageBox.Show("Exam Time is Finished");
}
}
}
If you want to format the Time Span value while assigning to Label... You can use below..
label1.Text = examTime.ToString(#"dd\.hh\:mm\:ss");
To do this properly, you will need to keep a track of when the timer was started
DateTime examStartTime;
System.Windows.Forms.Timer runTimer;
TimeSpan totalExamTime = new TimeSpan(1, 30, 0); // Set exam time to 1 hour 30 minutes.
if (runTimer == null)
runTimer = new System.Windows.Forms.Timer();
runTimer.Interval = 200;
runTimer.Tick -= new EventHandler(runTimerTick);
runTimer.Tick += new EventHandler(runTimerTick);
examStartTime = DateTime.Now;
runTimer.Start();
Then in the event handler you can do:
public void runTimerTick(object sender, EventArgs e)
{
TimeSpan currentExamTime = DateTime.Now - examStartTime;
if (currentExamTime > totalExamTime)
{
MessageBox.Show("Exam Time is Finished");
runTimer.Stop();
runTimer.Tick -= new EventHandler(runTimerTick);
runTimer.Dispose();
}
}
I hope this helps.
try this hope this will work for u
set timer interval=1000
minremain=1200000; //Should be in milisecond
timerplurg.satrt();
private void timerplurg_Tick(object sender, EventArgs e)
{
minremain = minremain - 1000; //substring One second from total time
string Sec = string.Empty;
if (minremain <= 0)
{
lblpurgingTimer.Text = "";
timerplurg.Stop();
return;
}
else
{
var timeSpan = TimeSpan.FromMilliseconds(Convert.ToDouble(minremain));
var seconds = timeSpan.Seconds;
if (seconds.ToString().Length.Equals(1))
{
Sec = "0" + seconds.ToString();
}
else
{
Sec = seconds.ToString();
}
string Totaltime = "Remaing Second: " + Sec;
lblpurgingTimer.Text = Totaltime;
}
How to set the onStart() method of window service so that after installing it first execute at 12 am,time interval is working fine,and service is executing after mentioned time interval, but not start at given time.
public static System.Timers.Timer Timer;
Double _timeinterval = 300 * 1000;// 6 mins
protected override void OnStart(string[] args)
{
Timer = new System.Timers.Timer();
Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
Timer.Interval = _timeinterval;
Timer.Enabled = true;
//method call to do operation
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
//method call to do operation
}
protected override void OnStart(string[] args)
{
aTimer = new System.Timers.Timer();
string starttime = "01.25";
//start time is 01.25 means 01:15 AM
double mins = Convert.ToDouble(starttime);
DateTime t = DateTime.Now.Date.AddHours(mins);
TimeSpan ts = new TimeSpan();
// ts = t - System.DateTime.Now;
ts = t.AddDays(1) - System.DateTime.Now;
if (ts.TotalMilliseconds < 0)
{
ts = t.AddDays(1) - System.DateTime.Now;
// ts = t - System.DateTime.Now;
}
_timeinterval = ts.TotalMilliseconds;
// _timeinterval now set to 1:15 am (time from now to 1:15AM)
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
aTimer.Interval = _timeinterval;
aTimer.Enabled = true;
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
// operation to perform
aTimer.Interval = 86400000; // now interval sets to 24 hrs
}