Use of Timer in Windows Service

30,540

Solution 1

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.

Solution 2

I would not recommend System.Timers.Timer since it silently eats unhandled exceptions and therefore hides errors that you should fix. imho better that your code blows up in your face if you do not handle exceptions properly.

As for System.Threading.Timer I tend to use the Change method to start/stop the timer in a pattern like this:

public class MyCoolService
{
    Timer _timer;

    public MyCoolService()
    {
        _timer = new Timer(MyWorkerMethod, Timeout.Infinite, Timeout.Infinite);
    }

    protected void OnStart()
    {
        _timer.Change(15000, Timeout.Infinte);
    }

    protected void MyWorkerMethod()
    {
        //pause timer during processing so it
        // wont be run twice if the processing takes longer
        // than the interval for some reason
        _timer.Change(Timeout.Infinite, Timeout.Infinite); 

        try
        {
            DoSomeWork();
        }
        catch (Exception err)
        {
            // report the error to your manager if you dare
        }

        // launch again in 15 seconds
        _timer.Change(15000, Timeout.Infinite);
    }

}

Solution 3

This is how you do it simply

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.IO;

  namespace MyService
{
    public partial class Service1 : ServiceBase
    {
        Timer myTimer;
        int x = 0;
        public Service1()
         {
             InitializeComponent();
         }

         protected override void OnStart(string[] args)
         {

             myTimer = new Timer(10000);                                // Sets a 10 second interval
             myTimer.Elapsed +=new ElapsedEventHandler(myTimer_Elapsed);// Specifies The Event Handler
             myTimer.Enabled = true;                                    // Enables the control
             myTimer.AutoReset = true;                                  // makes it repeat
             myTimer.Start();                                           // Starts the interval




         }
         protected void myTimer_Elapsed(object sender, ElapsedEventArgs e)
         {
             // All the Cool code that you need to run eg. Making a new file every 10 seconds
             x++;
             StreamWriter myFile = new StreamWriter("MyFile" + x.ToString() + ".txt");
             myFile.Write("Something");
             myFile.Close();
         }
         protected override void OnStop()
         {
         }
     }
 }

The Code above is the whole service with the timer. I realize this is an old post but it took me hours to figure this out. Hopefully it helps someone out there.

Solution 4

Here you have example how to use Timer in Windows Service.

Solution 5

This should just be a case of firing up a System.Timers.Timer with the right Interval (and AutoReset set to true), and handling Elapsed (but watch out; the callback is not on any particular thread).

MSDN has an example: http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed.aspx

also from MSDN:

The Timer component is a server-based timer, which allows you to specify a recurring interval at which the Elapsed event is raised in your application. You can then handle this event to provide regular processing. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. You could create a service that uses a Timer to periodically check the server and ensure that the system is up and running. If the system is not responding, the service could attempt to restart the server or notify an administrator.

The server-based Timer is designed for use with worker threads in a multithreaded environment. Server timers can move among threads to handle the raised Elapsed event, resulting in more accuracy than Windows timers in raising the event on time.

Share:
30,540
Parth Bhatt
Author by

Parth Bhatt

I am iPhone and iPad developer. https://github.com/akashraje/BidirectionalCollectionViewLayout ^[-_,A-Za-z0-9]$ NSRegularExpression *reg = [NSRegularExpression regularExpressionWithPattern:@"(#[a-zA-Z0-9_-]+)" options:NSRegularExpressionCaseInsensitive error:nil]; NSString *stringData = @"This is Parth known as #parth and this is an awesome place. I am fan of #scganguly."; int count = [reg numberOfMatchesInString:stringData options:0 range:NSMakeRange(0, [stringData length])]; NSLog(@"%d",count); if(count>0) { NSArray *array = [reg matchesInString:stringData options:0 range:NSMakeRange(0, [stringData length])]; NSLog(@"%@",array); NSMutableArray *stringArray = [[NSMutableArray alloc] init]; for (NSTextCheckingResult *result in array) { NSString *stringFinal = [stringData substringWithRange:result.range]; if(stringFinal != nil) { [stringArray addObject:stringFinal]; } } NSLog(@"stringArray: %@",stringArray); } For @user: @"(@[a-zA-Z0-9_]+)" NSLog(@"Request String: %@", requestString); NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]]; // NSString *fileLoc = [[NSBundle mainBundle] pathForResource:@"url" ofType:@"plist" ]; // NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc]; // NSString *urlLoc = [fileContents objectForKey:@"baseURL"]; NSString *urlLoc = @"http://portal.abc.com/candidate/post-info"; NSLog(@"URL is %@",urlLoc); NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: urlLoc]]; NSString *postLength = [NSString stringWithFormat:@"%d", [requestData length]]; [request setHTTPMethod: @"POST"]; [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; [request setHTTPBody: requestData]; http://blog.stackoverflow.com/archive/ https://developer.apple.com/library/prerelease/ios/documentation/General/Conceptual/CocoaTouch64BitGuide/Introduction/Introduction.html http://nscookbook.com/2013/03/ios-programming-recipe-19-using-core-motion-to-access-gyro-and-accelerometer/ http://code4app.net/category/coremotion http://www.devx.com/wireless/Article/44799 upload audio file to php ios Android post request on IOS https://developers.facebook.com/docs/ios/share https://github.com/oliverbarreto/FastFavs/blob/master/TODO2.h

Updated on July 03, 2022

Comments

  • Parth Bhatt
    Parth Bhatt almost 2 years

    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?

  • Parth Bhatt
    Parth Bhatt about 13 years
    Hey Thanks Jon Skeet..!! Can you please tell me where exactly I can see the output of my Console.WriteLine("");? I am a newbie.
  • Jon Skeet
    Jon Skeet about 13 years
    @PARTH: Well these are sample console applications - I just compiled and ran them on the command line. They're only meant to demonstrate how to set up and start a timer. You wouldn't usually use Console.WriteLine in a Windows Service. There are lots of tutorials around on the general aspects of writing a Windows Service - I was just focusing on the specific task of starting a timer.
  • Parth Bhatt
    Parth Bhatt about 13 years
    Hey Jon This works for 10 seconds only But I want that it should keep on doing this 24 x 7 then it that case what can be the modifications?
  • Jon Skeet
    Jon Skeet about 13 years
    @PARTH: In a Windows Service, you would start the timer from the "Start" event or whatever. This finishes after 10 seconds because the main thread exits. That doesn't happen in a Windows Service. I suggest you read up on the lifecycle of a Windows Service for more information.
  • Parth Bhatt
    Parth Bhatt about 13 years
    So if I am not wrong, you mean to say Thread.Sleep(10000) will not be required in Windows Service?
  • Jon Skeet
    Jon Skeet about 13 years
    @PARTH: Exactly. It's just for the purposes of the sample.
  • Parth Bhatt
    Parth Bhatt about 13 years
    Thanks Jon for all your help :). Yeah then it is fine. Rest of the code I suppose would remain the same. Am I right? Also is timer.AutoReset = true; is not required in windows Service, right?
  • Jon Skeet
    Jon Skeet about 13 years
    @PARTH: You want it to be true by the sounds of it, but the default is already true.
  • Parth Bhatt
    Parth Bhatt about 13 years
    Ok it is working in console application but when I try to put the same code in WindowsService on the OnStart() event then it does not call the PerformTimerOperation method. In windows service I am creating a new file under 'PerformTimerOperation`.
  • Jon Skeet
    Jon Skeet about 13 years
    @PARTH: Are you sure that it's not trying to create the file, but failing due to permissions? Try just writing to the event log, or something else that you'll be able to use for diagnostic purposes.
  • Parth Bhatt
    Parth Bhatt about 13 years
    Hey Jon, Thanks for the reply. This did work for me.Thanks "Master at Work"(Jon Skeet)..!! Thanks a lot :)
  • Nick Binnet
    Nick Binnet almost 11 years
    "new Timer(MyWorkerMethod, Timeout.Infinite, Timeout.Infinite);" has syntax error.
  • Nick Binnet
    Nick Binnet almost 11 years
    Yes, that's System.Threading.Timer. Produces error on .net Framework 4.0 Client Profile.
  • jgauffin
    jgauffin almost 11 years
    Well. It should be there according to the documentation: msdn.microsoft.com/en-us/library/2x96zfy7.aspx. Maybe you have to use an object state argument in the thread method.
  • Nick Binnet
    Nick Binnet almost 11 years
    I added 'object state' to the MyWorkerMethod method as well. :)
  • Mr Heelis
    Mr Heelis over 6 years
    what is the object state syntax?
  • jgauffin
    jgauffin over 6 years
    @MrHeelis: protected void MyWorkerMethod(object state)
  • Mr Heelis
    Mr Heelis over 6 years
    thanks, I just passed null in the end _timer = new Timer(MyWorkerMethod, null, Timeout.Infinite, Timeout.Infinite);