Build a pair of
TimeSpan
objects (startTime and endTime)
Then at some
appropriate interval (using a Timer) check if
DateTime.Now.TimeOfDay
is between your limits.
[Edit: flesh it out and tune it up...
No polling!!]
using System;
using System.Threading;
static void Main(string[] args)
{
TimeSpan testNow = DateTime.Now.TimeOfDay;
testNow = new TimeSpan(12, 0, 0);
TimesAreInputSoSetupProcessing(10, 15, 14, 30, testNow);
testNow = new TimeSpan(9, 0, 0);
TimesAreInputSoSetupProcessing(10, 15, 14, 30, testNow);
testNow = new TimeSpan(20, 0, 0);
TimesAreInputSoSetupProcessing(10, 15, 14, 30, testNow);
testNow = new TimeSpan(12, 0, 0);
TimesAreInputSoSetupProcessing(21, 15, 13, 30, testNow);
testNow = new TimeSpan(18, 0, 0);
TimesAreInputSoSetupProcessing(21, 15, 13, 30, testNow);
}
private static Timer beginTimer;
private static Timer stopTimer;
private static readonly TimeSpan OneDay = new TimeSpan(1, 0, 0, 0);
static void TimesAreInputSoSetupProcessing(int startHr, int startMin, int endHr, int endMin, TimeSpan now)
{
TimeSpan startTime = new TimeSpan(startHr, startMin, 0);
TimeSpan endTime = new TimeSpan(endHr, endMin, 0);
TimeSpan untilBegin = startTime - now;
TimeSpan untilStop = endTime - now;
if (startTime < endTime)
{
if (startTime <= now && now < endTime)
{
untilBegin = TimeSpan.Zero;
}
}
else if (now < endTime || startTime <= now)
{
untilBegin = TimeSpan.Zero;
}
if (untilBegin < TimeSpan.Zero)
untilBegin += OneDay;
if (untilStop < TimeSpan.Zero)
untilStop += OneDay;
Console.WriteLine("startTime: {0}, endTime: {1}, now: {2}", startTime, endTime, now);
Console.WriteLine("untilBegin: {0}", untilBegin);
Console.WriteLine("untilStop: {0}", untilStop);
}
static void BeginSomething(object state)
{
}
static void StopSomething(object state)
{
}
Note: these are all
static
because I was just using a Console App. They don't need to be static in the general case.
The Timers are setup to repeat every day.