Rishabh Jain
Rishabh Jain

Reputation: 41

How to trigger an event every specific time interval in C#?

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#?

Upvotes: 2

Views: 12631

Answers (4)

Phillip Ngan
Phillip Ngan

Reputation: 16126

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);
    }
}

Upvotes: 7

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

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!");
    }
}

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117175

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!

Upvotes: 2

TomTom
TomTom

Reputation: 62157

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).

Upvotes: 1

Related Questions