Search code examples
c#.nettimerdelay

Periodically Run a Method


In C# I would like to run a method every 30 seconds. For example, in a while loop it would run ReadData() every 30 seconds. ReadData goes out to collect data, analyzes, and stores it.

I understand that Thread.Sleep would pause the thread and the UI. Which for a few milliseconds might not be an issue, but for 30 seconds it definitely would. Is there another way to do this.

The limitation is that the application must be run using .NET 4.0 or less.


Solution

  • It sounds like you are doing some sort of polling at a fixed interval which is easy enough to implement with a timer as described in my example bellow. However, one thing to think about is the unnecessary overhead of polling in general. As an alternative I would like to suggest an asynchronous solutions instead where you only need to react to events when they occur and not on a fixed schedule. A typical implementation of this in the .Net realm is queue based systems, and a great product that makes this really easy is NServiceBus.

    Anyway, bellow is the timer code:

    Here is an example of a timer from msdn

    http://msdn.microsoft.com/en-us/library/system.timers.timer(v=vs.110).aspx

    public class Example
    {
       private static Timer aTimer;
    
       public static void Main()
       {
            // Create a timer with a two second interval.
            aTimer = new System.Timers.Timer(2000);
            // Hook up the Elapsed event for the timer. 
            aTimer.Elapsed += OnTimedEvent;
            aTimer.Enabled = true;
    
            Console.WriteLine("Press the Enter key to exit the program... ");
            Console.ReadLine();
            Console.WriteLine("Terminating the application...");
       }
    
        private static void OnTimedEvent(Object source, ElapsedEventArgs e)
        {
            Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
        }
    }