2

the timer needs to be run as a thread and it will trigger an event every fixed interval of time. How can we do it in c#?

Rishabh Jain
  • 41
  • 1
  • 2
  • 11

4 Answers4

7

Here's a short snippet that prints out a message every 10 seconds.

using System;
public class AClass
{
    private System.Timers.Timer _timer;
    private DateTime _startTime;

    public void Start()
    {
        _startTime = DateTime.Now;
        _timer = new System.Timers.Timer(1000*10); // 10 seconds
        _timer.Elapsed += timer_Elapsed;
        _timer.Enabled = true;
        Console.WriteLine("Timer has started");
    }

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        TimeSpan timeSinceStart = DateTime.Now - _startTime;
        string output = string.Format("{0},{1}\r\n", DateTime.Now.ToLongDateString(), (int) Math.Floor( timeSinceStart.TotalMinutes));
        Console.Write(output);
    }
}
Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79
1

Use one of the multiple timers available. Systme.Timer as a generic one, there are others dpending on UI technology:

  • System.Timers.Timer
  • System.Threading.Timer
  • System.Windows.Forms.Timer
  • System.Web.UI.Timer
  • System.Windows.Threading.DispatcherTimer

You can check Why there are 5 Versions of Timer Classes in .NET? for an explanation of the differences.

if you need something with mroore precision (down to 1ms) you an use the native timerqueues - but that requies some interop coding (or a very basic understanding of google).

Community
  • 1
  • 1
TomTom
  • 61,059
  • 10
  • 88
  • 148
  • Can you please give me a sample code such that it will call a function f() every 10 seconds? – Rishabh Jain Feb 08 '14 at 09:05
  • Note that will will probably never get it to execute once every 1ms. windows is not a real-time system. – Emond Feb 08 '14 at 09:10
  • Actually it will. High precision timers were made for exactly this. There are small fluctuations but those are automatically adjusted for. I have successfully used them to schedule forexample video playback from a recoding with a decoding stack that has no synchronization source. – TomTom Feb 08 '14 at 10:51
  • @user3235018 ontrary to most people I do believe that one should not frown upon such things are learning by reading documentation and that a programmer should know enough google-fu to solve a trivial issue like this when knowing the classes. – TomTom Feb 08 '14 at 10:52
1

I prefer using Microsoft's Reactive Framework (Rx-Main in NuGet).

var subscription =
    Observable
        .Interval(TimeSpan.FromSeconds(1.0))
        .Subscribe(x =>
        {
            /* do something every second here */
        });

And to stop the timer when not needed:

subscription.Dispose();

Super easy!

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
1

You can use System.Timers.Timer

Try This:

class Program
{
    static System.Timers.Timer timer1 = new System.Timers.Timer();
    static void Main(string[] args)
    {
        timer1.Interval = 1000;//one second
        timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick);
        timer1.Start();
        Console.WriteLine("Press \'q\' to quit the sample.");
        while (Console.Read() != 'q') ;
    }
    static private void timer1_Tick(object sender, System.Timers.ElapsedEventArgs e)
    {
        //do whatever you want 
        Console.WriteLine("I'm Inside Timer Elapsed Event Handler!");
    }
}
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67