settting in code a timer to run prgram. - c#

I have an application which I am running using windows scheduler every 30 minutes, I also have a config file which is a datatable called config. I am going through each of the rows, which has a schedule column and if the time is in the 30 minute window the program should run the whole program. The time windows are 12:00:00 and 12:30:00 and so on, as can be seen I'm checking the current time and the row time as can be seen blow, how would I make it run?
I tried the if statement below to see if it runs are the current time only and it doesn't work any ideas why this would be
TimeSpan time = DateTime.Now.TimeOfDay;
TimeSpan runningTime = DateTime.Parse(dr["scheduledTime"].ToString()).TimeOfDay;
if (time == runningTime)

If the time isn't exactly on the hour or half past the hour, the code in your if statement won't run, try this instead:
TimeSpan time = DateTime.Now.TimeOfDay;
TimeSpan runningTime = DateTime.Parse(dr["scheduledTime"].ToString()).TimeOfDay;
if (time >= runningTime && time <= (runningTime + new TimeSpan(0, 30, 0)))
When your program runs, DateTime.Now.TimeOfDay will contain something similar to 13:27:37, which obviously won't be equal to 13:00:00. So all you do is check that the current time is within the 30 minute window. We achieve that by checking that the current time elapsed since midnight (which is what .TimeOfDay on a DateTime gives you) is greater than or equal to the time elapsed since midnight of the TimeSpan you retrieve from your DataTable, and that it is also less than or equal to that same time slot plus 30 minutes.

Related

C# - most efficient way of measuring ellapsed time

I am working on a C# console application in which I need to know the ellapsed time since the program has started.
I have a variable that stores the time on start (DateTime now = DateTime.Now;)
What is the most efficient way of measuring the ellapsed time?
The ellapsed time can be hours - this is why I am concerned about efficiency and memory usage.
Thanks in advance!
Subtract the current time from the time the program started. This will return a TimeSpan which exposes properties like TotalHours which you can use to calculate the elapsed time.
// on start
var startTime = DateTime.UtcNow;
// later on, to see hours elapsed since then
var elapsed = (DateTime.UtcNow - startTime).TotalHours;
Don't worry. Measuring a time span does not use any resources, as it just compares now with then.
DateTime start = DateTime.Now;
// do some heavy calculation
TimeSpan delta = DateTime.Now - start; // get the time that elapsed
This does not use any resources except the variable for the start, which is just a 64 bit counter.
Note that for short timespans you're better off using Stopwatch, as this is not subject to time adjustments that may happen between start and now.

Calculating a timeout that is suspended during certain periods

I've been tasked with writing a method that calculates, given a start datetime and timeout in minutes, the datetime that the timeout should occur.
However the timeout should only 'tick' during certain times on certain days, which is determined by a non tick start datetime, non tick stop datetime and a list of open days.
For example, given the following:
Start datetime: Friday 21/02/2014 15:00
Timeout: 720 minutes (12 hours)
Open days: Monday,Tuesday,Wednesday,Thursday,Friday
Non tick start time: 09:00
Non tick stop time: 18:30
The calculated timeout datetime should be Monday 24/02/2014 17:30 (as it does not tick on Saturday and Sunday).
I'm writing this in C#, but its technically language agnostic.
Is there an 'elegant' way of doing this? Or is it simply a case of looping and adding additional time where its determined that timeout should stop ticking?
If you set up a timer to tick every period (e.g. every second), you can increment a number of ticks in the timer's callback handler.
I would approach in one of the following ways. Either I could run the callback every second no matter what, and in the callback I could check whether I'm suppose to increment or skip the increment for this period (inside the non-tick time period).
Otherwise, I could increment every time no matter what, and then have a check to see if the non-tick period is approaching and, if so, then adjust the timer's callback time to run the next callback after the non-tick time period has elapsed.

execute command 10 seconds before alarm

I am working on a project that allows me to create a program and give it tasks. Right now I am working on where I can tell it to set an alarm. The alarm feature works well, but I have a problem. When I set the alarm, I can say "goodnight" and then the program turns my monitor off into sleep mode. When the alarm goes off I want it to turn the monitor back on 10 or 15 seconds before it executes the code that happens when the alarm goes off.
Here is a bit of my code:
DateTime now = DateTime.Now;
string time = now.GetDateTimeFormats('t')[0];
if (time == Settings.Default.Alarm && Settings.Default.AClockEnbl == true)
{
SetMonitorInState(MonitorState.MonitorStateOn);
}
if (time == Settings.Default.Alarm && Settings.Default.AClockEnbl == true)
{
//All other alarm code
}
I want the first if statement to tell the command to happen 10 seconds before Settings.Default.Alarm
Can anybody help?
If you add 15 seconds to the DateTime now and compare that to the Alarm time, you can use that to turn on the monitor.
Then you can execute the rest of the code when now (without the extra 15 seconds) equals the alarm time.
As mentioned in comments you'll want to compare with DateTime's instead of strings and use TimeSpan to increment 15 seconds.
You can use a TimeSpan to offset your date:
beforeTime = now + TimeSpan.FromSeconds(15);
then compare Settings.Default.Alarm with beforeTime.GetDateTimeFormats('t')[0] in order to turn on the monitor.
This said, try to refactor your code and get rid of those strings. Use DateTime and TimeSpan or ms since Epoch in an int if you really want, but not strings.

How can I express a time duration in seconds?

I'm reading some specifications and there is one point that says I need a variable that will represent time in seconds. Maybe this is an easy question, but how can I express a time duration in seconds in C#?
Store the time in a TimeSpan type object and then you can get total seconds through TimeSpan.TotalSeconds property
TimeSpan ts = new TimeSpan(1, 10, 30); // 1 hour , 10 mins and 30 seconds.
double seconds = ts.TotalSeconds;

inaccurate .NET timer?

I'm developing an application and I need to get the current date from a server (it differs from the machine's date).
I receive the date from the server and with a simple Split I create a new DateTime:
globalVars.fec = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(infoHour[0]), int.Parse(infoHour[1]), int.Parse(infoHour[2]));
globalVars is a class and fec is a public static variable so that I can access it anywhere in the application (bad coding I know...).
Now I need to have a timer checking if that date is equal to some dates I have stored in a List and if it is equal I just call a function.
List<DateTime> fechas = new List<DateTime>();
Before having to obtain the date from a server I was using computer's date, so to check if the dates matched I was using this:
private void timerDatesMatch_Tick(object sender, EventArgs e)
{
DateTime tick = DateTime.Now;
foreach (DateTime dt in fechas)
{
if (dt == tick)
{
//blahblah
}
}
}
Now I have the date from the server so DateTime.Now can't be used here. Instead I have created a new timer with Interval=1000 and on tick I'm adding 1 second to globalVars.fec using:
globalVars.fec = globalVars.fec.AddSeconds(1);
But the clock isn't accurate and every 30 mins the clock loses about 30 seconds.
Is there another way of doing what I'm trying to do? I've thought about using threading.timer instead but I need to have access to other threads and non-static functions.
Store the difference between the server's time and local time. Calculate the servers' time when you need it using that difference.
If you create atimer with an interval of 1000ms, it will be called no sooner than 1000ms. So you can pretty much guarantee that it will be called in more than 1000ms, which means you will "lose" time by adding 1s on this timer tick - This will accumulate error with every tick. A better approach is to record a start time and use the current time to determine the current offset from that known start time, so that you don't accumulate any error in your time keeping. (There will still be some error, but you will not drift out of touch with real-time over time)
Different timers (Forms.Timer, Thread.Timer etc) will give different accuracies as well - Forms.Timer is particularly poor for accuracy.
You could also use a high performance time to keep track of the time better - see here, for example.
Here is a reliable 1 μs Timer
See https://stackoverflow.com/questions/15725711/obtaining-microsecond-precision-using-net-without-platform-invoke?noredirect=1#comment22341931_15725711
I guarantee its faster and more accurate then StopWatch and PerformanceCounters and uses the fractions of a second you have in the time slice wisely!

Categories

Resources