Use of Timer in Windows Service

后端 未结 6 2027
轻奢々
轻奢々 2020-12-12 23:08

I have a windows service where in I want to create a file every 10 seconds.

I got many reviews that Timer in Windows service would be the best option.

How ca

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-12 23:34

    Firstly, pick the right kind of timer. You want either System.Timers.Timer or System.Threading.Timer - don't use one associated with a UI framework (e.g. System.Windows.Forms.Timer or DispatcherTimer).

    Timers are generally simple

    1. set the tick interval
    2. Add a handler to the Elapsed event (or pass it a callback on construction),
    3. Start the timer if necessary (different classes work differently)

    and all will be well.

    Samples:

    // System.Threading.Timer sample
    using System;
    using System.Threading;
    
    class Test
    {
        static void Main() 
        {
            TimerCallback callback = PerformTimerOperation;
            Timer timer = new Timer(callback);
            timer.Change(TimeSpan.Zero, TimeSpan.FromSeconds(1));
            // Let the timer run for 10 seconds before the main
            // thread exits and the process terminates
            Thread.Sleep(10000);
        }
    
        static void PerformTimerOperation(object state)
        {
            Console.WriteLine("Timer ticked...");
        }
    }
    
    // System.Timers.Timer example
    using System;
    using System.Threading;
    using System.Timers;
    // Disambiguate the meaning of "Timer"
    using Timer = System.Timers.Timer;
    
    class Test
    {
        static void Main() 
        {
            Timer timer = new Timer();
            timer.Elapsed += PerformTimerOperation;
            timer.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds;
            timer.Start();
            // Let the timer run for 10 seconds before the main
            // thread exits and the process terminates
            Thread.Sleep(10000);
        }
    
        static void PerformTimerOperation(object sender,
                                          ElapsedEventArgs e)
        {
            Console.WriteLine("Timer ticked...");
        }
    }
    

    I have a bit more information on this page, although I haven't updated that for a long time.

提交回复
热议问题