Wednesday, January 27, 2010

C# - Create Windows Service with Timer

Below is an example to create Windows Service with timer operation:

Ref.:
http://www.aspfree.com/c/a/C-Sharp/Timer-Objects-in-Windows-Services-with-C-sharp-dot-NET/1/

1. Use Visual Studio (C#) to select project of "Windows Service"

2. Include namespace of
using System.IO;
using System.Timers;

3. Double click "service1.cs" to change property (please refer to screen capture in above URL, to set nature to Auto-start). Change both of "Name" and "Service Name".

Name of project is "mcs_daily_report"
set name of service to "mcs_report"

3.1 Click on the hyperlink Add Installer (Click to select the file Service1.cs, in the center gray area of Visual Studio, click right button and select "Add Installer"). A design screen will be added to the project with 2 controls: serviceProcessInstaller1 and ServiceInstaller1. Click the serviceProcessInstaller1 control and, in the properties dialog, change the account to LocalSystem.

3.2 In the serviceInstaller control, change the start type to Automatic, and give it a nice display name.

4. Add code as below for timer operation

OnStart()
{ ....
Timer timer = new Timer();

timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
timer.Interval = 60000;
timer.Enabled = true;
timer.Start();
....
}

public static void OnElapsedTime(object source, ElapsedEventArgs e)
{
DateTime dtNow = System.DateTime.Now;

string strHeader = dtNow.ToString("yyyy-MM-dd HH:mm:ss");
LogToFile(1, strHeader);
}

5. Compile and execute as below for registration:

InstallUtil mcs_daily_report.exe
net start mcs_report

other commands for to remove/stop the service:

net stop mcs_report
InstallUtil /u mcs_daily_report.exe


6. Below are commands which can be used to write log in "Event Log"

public static EventLog g_myLog;

public OnStart()
{
....
this.AutoLog = false; // turn off event log

if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource("MySource", "MyLog");
}
// configure the event log instance to use this source name
g_myLog = new EventLog();
g_myLog.Source = "MySource";
g_myLog.WriteEntry("In OnStart.");
...
}

No comments: