Question

I am coding a C# WinForms program that I want to have running in the background 24/7. In an XML file, I'm pulling a time. For example: 3:30:00 PM. When I then display this time after parsing it, it comes out as 1/15/2014 3:30:00 PM.

What my question is, based on this XML value, how can I have it so that, at 3:30:00 PM every day, a Timer object or something displays a message box or some other action?

Was it helpful?

Solution

Your idea of using a Timer is good. You could use either the Winforms Timer or System.Timers.Timer. In this case, I will refer to System.Timers.Timer as I have some code I can base this answer off of.

Anyway, just assign it an Interval and give an event to fire via Elapsed. Then in the code that Elapsed calls, put in your action code. Finally, start the timer wherever you need it and try running it.

If you are using a DateTime to hold the file data, then you will need to either create a constant number of milliseconds until the next day (not recommended), or do some math using TimeSpans (hint: use the constructor to get the time). The TimeSpan contains a property called 'TotalMilliseconds' that you can use as the Interval.

I hope this points you in the right direction.

OTHER TIPS

That is a console application that executes a job at a fixed time every day

using System;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        public static void Main()
        {
            Timer t = new Timer(TimerCallback, null, 0, 2000);
            // Wait for the user to hit <Enter>
            Console.ReadLine();
        }

        private static void TimerCallback(Object o)
        {
            Console.WriteLine("In TimerCallback: " + DateTime.Now);
            DateTime s = DateTime.Now;
            TimeSpan ts = new TimeSpan(23, 27, 0);
            s = s.Date + ts;
            if (DateTime.Now > s && !fired) 
            { 
                Console.WriteLine("Do the Job");
                fired = true;
            }
            else if (DateTime.Now < s)
            {
                fired = false;
            }
        }
        private static bool fired = false;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top