Short of following Heslacher's advice on a Timer, see RobH's comment regarding crossing dates. Then extend that thinking to any daylight saving transitions. You might say you are never going to run the app during the middle of the night, but in the future this app could be a service or a scheduled task that does run near midnight or 2 AM.
For internal timings, one should always prefer DateTime.UtcNow
over DateTime.Now
for 2 reasons: (1) its faster and (2) its not error prone to DST transitions.
You may think in terms of just time for your XML, but you would be safer and using better practices if you passed an ISO 8601 compliant string. This is easy to do with .NET by using the Round-trip "O" Format Specifier. Strongly recommend you carefully read the link on Round-trip.
This simplifies your coding while making the app less error prone. Assuming the variable LastSuccessTime
is a time string as read from the XML, you no longer have to take a lot of steps to parse out pieces of it. Your XML would look like:
<MyXML>
<LastTimeTaskRun>2016-06-21T23:59:00Z</LastTimeTaskRun>
</MyXML>
Such that LastSuccessTime
would contain "2016-06-21T23:59:00Z".
Now you could use code like:
var lastSuccessUtc = DateTime.Parse(LastSuccessTime, null, DateTimeStyles.RoundtripKind).ToUniversalTime();
var isBigThen5Min = (DateTime.UtcNow - lastSuccessUtc).TotalMinutes > 5;
The last line contains a magic number, so you should consider making a constant for it. You can also get the same effect different ways (shown for example, not necessarily a better practice):
const int thresholdInMinutes = 5;
var isBigThen5Min = (DateTime.UtcNow - lastSuccessUtc) > TimeSpan.FromMinutes(tresholdInMinutes);
This answer would work across midnight across different dates and for DST transitions. Plus it shortens up the code. Shorter and simpler is easier to follow and maintain.
LastTimeTaskRun
is 23:59 and then you run at 00:02 the next day your code will incorrectly calculate a time difference greater than 5 minutes (when it's only 3). \$\endgroup\$