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 can I achieve this?
See Question&Answers more detail:osI 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 can I achieve this?
See Question&Answers more detail:osFirstly, 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
Elapsed
event (or pass it a callback on construction), 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.