How to get elapsed timed in Xamarin forms - c#

I want my timer to continue from the time I started it until now, I need help with the logic that uses timespan to calculate the elapsed time from the minutes the timer started to the current time, Here is what I have done:
CancellationTokenSource cts = _cancellationTokenSource; // safe copy
//Timer Starts here
_TimeSpan = TimeSpan.FromMinutes(TimeSheet.TotalTime);
//Increment timer by a second interval
Device.StartTimer(TimeSpan.FromSeconds(1), () => {
if (cts.IsCancellationRequested)
{
return false;
}
else
{
Device.BeginInvokeOnMainThread(() => {
_TimeSpan += TimeSpan.FromSeconds(1);
displaytime = _TimeSpan.ToString(#"h\:m\:s");
TimeSheet.TotalTimeForDisplay = displaytime;
Console.WriteLine("Timer");
Console.WriteLine(displaytime);
});
return true;
}

use System.Timers.Timer
// use whatever start time you need
DateTime start = DateTime.Now;
// 1000ms = 1s
System.Timers.Timer timer = new System.Timers.Timer(1000);
timer.Elapsed += OnTimedEvent;
timer.Start();
then
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
var elapsed = DateTime.Now - start;
}

Related

Set Time Interval in Timer in Xamarin

In my Xamarin App, I want to set the timer interval for timer e.g. Start after 5 seconds and run for 10 seconds.
Here is my code sample
Device.StartTimer(TimeSpan.FromSeconds(5), () =>
{
FaceIdentityInstruction = "Look Down";
return false;
});
You could add System.Timers after Device.StartTimer 5 seconds.
private static System.Timers.Timer aTimer;
static int count = 0;
public PageListView()
{
InitializeComponent();
Console.WriteLine("Timer prepare for running");
Device.StartTimer(TimeSpan.FromSeconds(5), () =>
{
Console.WriteLine("Timer run");
aTimer = new System.Timers.Timer(1000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += OnTimedEvent;
aTimer.AutoReset = true;
aTimer.Enabled = true;
return false;
});
}
private static void OnTimedEvent(Object source, ElapsedEventArgs e)
{
count++;
if (count==10)
{
aTimer.Stop();
Console.WriteLine("Timer Stop");
}
}
The output:
10-23 10:34:14.250 I/mono-stdout(29128): Timer prepare for running
10-23 10:34:19.262 I/mono-stdout(29128): Timer run
10-23 10:34:29.286 I/mono-stdout(29128): Timer Stop

Check if the countdown timer is 0

I have a script based on the countdown timer. I want that when the time reaches 0, the timer stop and a message appear. The code id this:
public partial class simulare : Form
{
private admin admin;
Timer timer = new Timer();
public simulare(admin admin)
{
InitializeComponent();
this.admin=admin;
label2.Text = TimeSpan.FromMinutes(0.1).ToString();
}
private void simulare_Load(object sender, EventArgs e)
{
var startTime = DateTime.Now;
timer = new Timer() { Interval = 1000 };
timer.Tick += (obj, args) =>
label2.Text = (TimeSpan.FromMinutes(0.1) - (DateTime.Now - startTime)).ToString("hh\\:mm\\:ss");
timer.Enabled = true;
timer.Start();
if (condition)
{
timer.Stop();
MessageBox.Show("Done!");
}
}
}
I tried those conditions, but unsuccessful:
if (timer.ToString() == TimeSpan.Zero.ToString())
if (label2.Text.ToString() == TimeSpan.Zero.ToString())
if (label2.Text == TimeSpan.Zero)
You could extract the calculation and assign the result to a TimeSpan variable, then check if the Seconds in that TimeSpan variable are equals to zero
void simulare_Load(object sender, EventArgs e)
{
var startTime = DateTime.Now;
timer = new System.Windows.Forms.Timer() { Interval = 1000 };
timer.Tick += (obj, args) =>
{
TimeSpan ts = TimeSpan.FromMinutes(0.1) - (DateTime.Now - startTime);
label1.Text = ts.ToString("hh\\:mm\\:ss");
if (ts.Seconds == 0)
{
timer.Stop();
MessageBox.Show("Done!");
}
};
timer.Start();
}
First off, checking anything in the Load event isn't going to work. That code only runs once (on form load).
So you need a more complex tick event, which I would put into an actual function instead of a lambda:
private int countDown = 50; //Or initialize at load time, or whatever
public void TimerTick(...)
{
label2.Text = (TimeSpan.FromMinutes(0.1) - (DateTime.Now - startTime)).ToString("hh\\:mm\\:ss");
countDown--;
if (countDown <= 0)
timer.Stop();
}
I use an int counter here since checking against a view property (the text in this case) isn't a very good design/practice. If you really want a TimeSpan, I would still save it off instead of checking directly against the Text property or a string.

Timer C# use in game development

I have a game in C# and I need to allow tournament mode in which each round will be of 2 minutes. How can I display the time from 0:00 up till 2:00 on the form?
I have this in a constructor:
Timer timer = new Timer();
timer.Interval = 1000;
timer.Tick += new EventHandler(Timer_Tick);
timer.Start();
And this is the Event Handler
void Timer_Tick(object sender, EventArgs e)
{
this.textBox1.Text = DateTime.Now.ToLongTimeString();
}
but I don't know how I can begin the time from 0:00 instread of the current time.. I tried creating a DateTime instance but when I do myDateTime.ToString(); in the event handler, it just remains 0:00.
I tried searching but I can't find anything related.
Thanks a lot !
Save current time to field when you are starting timer:
_startTime = DateTime.Now;
timer.Start();
And calculate difference later:
void Timer_Tick(object sender, EventArgs e)
{
this.textBox1.Text = (DateTime.Now - _startTime).ToString(#"mm\:ss");
}
You need a member variable that is in scope for both the timer initialization and the Timer_Tick event handler.
class Something
{
DateTime _myDateTime;
Timer _timer;
public Something()
{
_timer = new Timer();
_timer.Interval = 1000;
_timer.Tick += Timer_Tick;
_myDateTime = DateTime.Now;
_timer.Start();
}
void Timer_Tick(object sender, EventArgs e)
{
var diff = DateTime.Now.Subtract(_myDateTime);
this.textBox1.Text = diff.ToString();
}
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
void Timer_Tick(object sender, EventArgs e)
{
label1.Text = stopWatch.ElapsedTicks.ToString();
}
You can store a DateTime.Now when you start the timer and then in every timer tick handler calculate how much time has passed between DateTime.Now and the stored start date. If you have a pause, you will need to also keep track of how long the game has been paused.
Considering the inconviniences with the above method, I would suggest you declare a StopWatch somewhere, instantiate and start it where you call timer.Start and then in your timer tick just read the Elapsed property of the StopWatch. You can even Stop and Start (pause) it if you need.

How to set the onStart() method of window service so that after installing it first execute at 12 am

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
}

Windows Service - How to make task run at several specific times?

I have a windows service running. Within it the task runs currently at 7pm every day.
What is the best way to have it run say fir example at 9.45am, 11.45am, 2pm, 3.45pm, 5pm and 5.45pm.
I know i can have scheduled task to run the function but i would like to know how to do this within my windows service. Current code below:
private Timer _timer;
private DateTime _lastRun = DateTime.Now;
private static readonly log4net.ILog log = log4net.LogManager.GetLogger
(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected override void OnStart(string[] args)
{
// SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
// test.Import();
log.Info("Info - Service Started");
_timer = new Timer(10 * 60 * 1000); // every 10 minutes??
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
_timer.Start();
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
log.Info("Info - Check time");
DateTime startAt = DateTime.Today.AddHours(19);
if (_lastRun < startAt && DateTime.Now >= startAt)
{
// stop the timer
_timer.Stop();
try
{
log.Info("Info - Import");
SmartImportService.WebService.WebServiceSoapClient test = new WebService.WebServiceSoapClient();
test.Import();
}
catch (Exception ex) {
log.Error("This is my error - ", ex);
}
_lastRun = DateTime.Now;
_timer.Start();
}
}
In case you dont want to go for cron or quartz, write a function to find time interval between now and next run and reset the timer accordingly, call this function on service start and timeelapsed event. You may do something like this (code is not tested)
System.Timers.Timer _timer;
List<TimeSpan> timeToRun = new List<TimeSpan>();
public void OnStart(string[] args)
{
string timeToRunStr = "20:45;20:46;20:47;20:48;20:49";
var timeStrArray = timeToRunStr.Split(';');
CultureInfo provider = CultureInfo.InvariantCulture;
foreach (var strTime in timeStrArray)
{
timeToRun.Add(TimeSpan.ParseExact(strTime, "g", provider));
}
_timer = new System.Timers.Timer(60*100*1000);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
ResetTimer();
}
void ResetTimer()
{
TimeSpan currentTime = DateTime.Now.TimeOfDay;
TimeSpan? nextRunTime = null;
foreach (TimeSpan runTime in timeToRun)
{
if (currentTime < runTime)
{
nextRunTime = runTime;
break;
}
}
if (!nextRunTime.HasValue)
{
nextRunTime = timeToRun[0].Add(new TimeSpan(24, 0, 0));
}
_timer.Interval = (nextRunTime.Value - currentTime).TotalMilliseconds;
_timer.Enabled = true;
}
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
_timer.Enabled = false;
Console.WriteLine("Hello at " + DateTime.Now.ToString());
ResetTimer();
}
Consider using Quartz.net and CronTrigger.
If u are clear abt what schedule it should run..then change time interval for timer in the timeelapsed event so that it runs according to schedule..i've never tried though
I would use a background thread and make it execute an infinite loop which does your work and sleeps for 15 minutes. It would be a lot cleaner and more simple for service code than using a timer.
See this article on MSDN.

Categories

Resources