In order to develop, it is often necessary to implement the function: allowing the server to run a fixed program (or implement a fixed operation) every day, such as backing up database data at 2:00 per day. To achieve such functions, we can use Windows Service. Windows Service is a system automatic, unattended program (only in Windows NT, 2000, and XP operating systems), which can start running at system startup. Users can access Windows Service via Service Control Manager (SCM) Applet or some special service-control applications, enabling the service before being logged in to the system without users.
Before .NET appeared, writing a Windows service is VC , and Delphi can do things.
VB must use a third party control to do, and write special complications. With Microsoft®.NET Framework, we can easily create a Windows service by creating applications installed as a service.
design:
A Windows service program runs the specified program at the specified time according to the configuration in the configuration file.
Process:
Start Service à Read Profile à Start Timer
Timer timing trigger (such as 30 seconds per 30 second) à cycle requires running component time à time to à run specified program
write:
Create a Windows Service
Rename Server1.cs is schedulerserver.cs,
Double-click SchedulerServer.cs to open the design page, drag the Timer control from the toolbar's components.
Renamed Schedulertimer and set enabled to flash.
Note that the Timer control inside Components, the Timer control inside Windows Forms is not.
F7 browsing code can see the following code
When the server is started:
///
/// set Things in Motion So your service can do its work.
///
protected override void onstart (String [] ARGS)
{
// Todo: add code here to start your service.
}
When the service is stopped:
///
/// stop this service.
///
protected override void onstop ()
{
// Todo: Add code Here to Perform Any Tear-Down Necessary to Stop Your Service.
}
Add a write log function to log the log:
Public Static Void WriteLog (String Strlog)
{
String strpath;
StrPath = system.environment.system.environment.systemdirectory;
StrPath = @ "/ schedulerServer.txt";
FILESTREAM FS = New FileStream (strpath, filemode.openorcreate, fileaccess.write);
Streamwriter M_StreamWriter = New StreamWriter (FS);
M_StreamWriter.Basestream.seek (0, seekorigin.end); m_streamwriter.writeline (strlog);
M_StreamWriter.flush ();
M_StreamWriter.Close ();
fs.close ();
}
Automatic service configuration file
The configuration file is saved in the system directory, Windows 2000 is WinNT / System32, file named SchedulerServer.xml, stores all configuration information for automatic service, let's see the format of SchedulerServer.xml:
FilePath sets the path to the components that you need to run
Runtime settings need to run time
If you need to run multiple programs, just add
Add a read configuration file function in the program:
Private bool readconf ()
{
Try
{
String strpath;
XMLDocument Xmldoc = new xmldocument ();
XMLNodelist Xmlnd;
StrPath = system.environment @ "/ schedulerserver.xml";
XMLDoc.Load (StrPath);
Xmlnd = Xmldoc.selectNodes ("SchedulerServer / AutoServer);
Arrconf = new string [2, xmlnd.count];
For (int i = 0; i
{
Arrconf [0, I] = XMLND [i] .selectsinglenode ("FilePath"). Innerxml.trim ();
Arrconf [1, I] = XMLND [i] .selectsinglenode ("runtime"). InnerXml.trim ();
}
Return True;
}
Catch (Exception E)
{
WriteLog (datetime.now.toString ());
WriteLog ("Read Configuration Error:");
WriteLog (e.tostring ());
Return False;
}
}
Start service:
Define two variables:
Private string [,] arrconf; save configuration information
Private assembly [] assobj; loading components
Add the following code in the onStart event:
protected override void onstart (String [] ARGS)
{
Writelog ("/ *************************************************** ************** / ");
Writelog ("ScheculerServer Start AT" DateTime.now.toString ()); // load configuation
IF (! ReadConf ()) return;
// load assembly
Try
{
Assobj = new assembly [arrconf.getlength (1)];
For (int i = 0; i
{
Assobj [I] = askMBLY.LOADFROM (ArrConf [0, i] .tostring ());
Arrconf [0, i] = "notruning";
}
}
Catch (Exception E)
{
WriteLog (datetime.now.toString ());
WriteLog ("Load DLL Error:");
WriteLog (e.tostring ());
}
// Start Time
Schedulertimer.Interval = 30000; // Setting every 30 seconds
Schedulertimer.enabled = true; // Start Timer
}
Timer triggers:
Do check whether the check time is run here
Private void schedulertimer_Elapsed (Object sender, System.Timers.ELAPSEDEventArgs E)
{
Try
{
//SCHEDULERTIMER.ENABLED=FALSE;
DateTime DTNOW = DATETIME.NOW;
Datetime DTRUN;
For (int i = 0; I
{
Dtrun = convert.todatetime (Arrconf [1, i] .tostring ());
IF (DTRUN.Addseconds (-30) <= DTNOW && DTNOW <= DTRUN.AddSeconds (30)) {
IF (ArrConf [0, I] .tostring (). Trim () == "notruning")
{
Foreach (Type T in Assobj [i] .gettypes ())
{
IF (T.Isclass &&! T.isabstract && T.ISPUBLIC)
{
Object obj = activator.createInstance (T);
MethodInfo mi = T. GetMethod ("run");
IF (mi! = null)
{
mi.invoke (Obj, null);
Obj = NULL;
Gc.collect ();
Break;
}
Obj = NULL;
Gc.collect ();
}
}
Arrconf [0, I] = "Onruning";
WriteLog ("--------------------------------------------- -------------- ");
Writelog (DateTime.now.toString () ": Runing" Arrconf [1, i] " assobj [i] .location.toString ());
WriteLog ("--------------------------------------------- -------------- ");
}
Catch (Exception EX)
{
WriteLog ("##################################################################### ########### ");
Writelog (ex.toswoting ());
WriteLog ("##################################################################### ########### ");
}
}
At this time, the main skeleton of the program is complete, the next step needs to make a Windows service installer, switch to the design page, with the upper right feet of the property, the Add Installer word, click, VS.NET to help you generate the installer.
Open the ProjectInstaller.cs file, you can see two components and set their properties.
Run the account Select Localsystem, and the system runs in the local system account.
Start type selection automatic.
Compile to EXE, open VS.NET CMD, enter the exe directory, run installutil.exe schedulerser.exe installation service, after success, open service management to see the service, start the service.
Service log Save SchedulerServer.txt in the system directory
/ ************************************************** *********** /
ScheculerServer Start AT 12/24/2003 3:46:21 PM
-------------------------------------------------- -----------
12/24/2003 3:46:51 PM: RUNING 15:47 E: /Work/geid/src/geidautocheck/bin/debug/geidautocheck.dll
-------------------------------------------------- -----------
ScheculerServer Stop At 12/24/2003 3:48:55 PM
/ ************************************************** *********** /
Automatically run the program:
1. .NET components (DLL)
2. Entry
Public void Run ()
{}
Start service:
Define two variables:
Private string [,] arrconf; save configuration information
Private assembly [] assobj; loading components
Add the following code in the onStart event:
protected override void onstart (String [] ARGS)
{
Writelog ("/ *************************************************** ************** / ");
Writelog ("ScheculerServer Start AT" DateTime.now.toString ());
// load configuation
IF (! ReadConf ()) return;
// load assembly
Try
{
Assobj = new assembly [arrconf.getlength (1)];
For (int i = 0; i
{
Assobj [I] = askMBLY.LOADFROM (Arrconf [0, i] .tostring ()); Arrconf [0, i] = "notruning";
}
}
Catch (Exception E)
{
WriteLog (datetime.now.toString ());
WriteLog ("Load DLL Error:");
WriteLog (e.tostring ());
}
// Start Time
Schedulertimer.Interval = 30000; // Setting every 30 seconds
Schedulertimer.enabled = true; // Start Timer
}
Timer triggers:
Do check whether the check time is run here
Private void schedulertimer_Elapsed (Object sender, System.Timers.ELAPSEDEventArgs E)
{
Try
{
//SCHEDULERTIMER.ENABLED=FALSE;
DateTime DTNOW = DATETIME.NOW;
Datetime DTRUN;
For (int i = 0; I
{
Dtrun = convert.todatetime (Arrconf [1, i] .tostring ());
IF (DTRUN.Addseconds (-30) <= DTNOW && DTNOW <= DTRUN.AddSeconds (30)) {
IF (ArrConf [0, I] .tostring (). Trim () == "notruning")
{
Foreach (Type T in Assobj [i] .gettypes ())
{
IF (T.Isclass &&! T.isabstract && T.ISPUBLIC)
{
Object obj = activator.createInstance (T);
MethodInfo mi = T. GetMethod ("run");
IF (mi! = null)
{
mi.invoke (Obj, null);
Obj = NULL;
Gc.collect ();
Break;
}
Obj = NULL;
Gc.collect ();
}
}
Arrconf [0, I] = "Onruning";
WriteLog ("--------------------------------------------- -------------- ");
Writelog (DateTime.now.toString () ": Runing" Arrconf [1, i] " assobj [i] .location.toString ());
WriteLog ("--------------------------------------------- -------------- ");
}
}
Catch (Exception EX)
{
WriteLog ("##################################################################### ########### ");
Writelog (ex.toswoting ());
WriteLog ("##################################################################### ########### ");
}
}
At this time, the main skeleton of the program is complete, the next step needs to make a Windows service installer, switch to the design page, with the upper right feet of the property, the Add Installer word, click, VS.NET to help you generate the installer. Open the ProjectInstaller.cs file, you can see two components and set their properties.
Run the account Select Localsystem, and the system runs in the local system account.
Start type selection automatic.
Compile to EXE, open VS.NET CMD, enter the exe directory, run installutil.exe schedulerser.exe installation service, after success, open service management to see the service, start the service.
Service log Save SchedulerServer.txt in the system directory
/ ************************************************** *********** /
ScheculerServer Start AT 12/24/2003 3:46:21 PM
-------------------------------------------------- -----------
12/24/2003 3:46:51 PM: RUNING 15:47 E: /Work/geid/src/geidautocheck/bin/debug/geidautocheck.dll
-------------------------------------------------- -----------
ScheculerServer Stop At 12/24/2003 3:48:55 PM
/ ************************************************** *********** /
Automatically run the program:
1. .NET components (DLL)
2. Entry
Public void Run ()
{}