Create a Windows Service (which can be used to implement scheduled tasks, event monitoring...). Net

Source: Internet
Author: User

What is a Windows service?

A Windows ServiceProgramIt is an executable application that can complete specific functions in a Windows operating system. Although a Windows service program is executable, it does not run as a normal executable file by double-clicking it. It must have a specific startup method. These methods include automatic start and Manual start. For automatically started Windows service programs, they are executed before the user logs on after Windows is started or restarted. You only need to register the corresponding Windows Service Program in Service Control Manager and set the startup category to Automatic startup. For a Windows service program that is manually started, you can use the net start command of the command line tool to start it, or start the corresponding Windows service program through the service item under the management tool in the control panel (see figure 1 ). Similarly, a Windows service program cannot be terminated as a normal application. Because Windows service programs generally do not have a user interface, you need to stop them using the command line tool or the tool shown in the figure below, or make the Windows Service Program stop automatically when the system is disabled. Because Windows service programs do not have a user interface, the user interface-based API functions have little significance for them. To enable a Windows service program to work normally and effectively in a system environment, programmers must implement a series of methods to complete its service functions. Windows service programs have a wide range of applications,Typical Windows service programs include hardware control, application monitoring, system-level applications, diagnostics, reports, web and file system services.

Implement task execution through time control timing Detection

An service1.cs file (rename service1.cs to scheduleservice. CS) is automatically created in the corresponding project (such as winservice1). Select this file and viewCode,

Using System;
Using System. serviceprocess;
Using System. Timers;

Namespace Winservice1
{
Public Partial Class Scheduleservice: servicebase
{
# Region Attribute Definition

/// <Summary>
/// Timer
/// </Summary>
Timer timer1;

# Endregion

Public Scheduleservice ()
{
Initializecomponent ();
Timer1 = New Timer ();
Servicename = "Scheduleservice" ;
Canstop = True ;
Canshutdown = True ;
Canpauseandcontinue = True ;
Autolog = True ;

Timer1.elapsed + = timerw.elapsed;
Timer1.integer = 1000;
Timer1.start ();
}

/// <Summary>
/// Reach the interval
/// </Summary>
Void Timersponelapsed ( Object Sender, elapsedeventargs E)
{
If (E. signaltime. Second = 0) // Execute once per minute
{
// Check whether there are tasks to be executed in the configuration file


If ( False )
{
Writelog ( "File 1" , "The task has been detected. The task to be executed is *** and scheduled to be executed" );
}
Else
Writelog ( "File 1" , "No task to be executed has been detected" );
}
}

Protected Override Void Onstart ( String [] ARGs)
{
Base . Onstart (ARGs );
Writelog ( "File 1" , "Winservice1.onstart" +"Service start" );
}

Protected Override Void Onstop ()
{
Base . Onstop ();
Writelog ( "File 1" , "Winservice1.onstop" + "Service stopped" );
}

# Region Log

Private Static String Logpath = String . Empty;
/// <Summary>
/// Folder for saving logs
/// </Summary>
Public Static String Logpath
{
Get
{
If (Logpath =String . Empty)
{
If (System. Web. httpcontext. Current = Null )
// Windows Forms Application
Logpath = appdomain. currentdomain. basedirectory;
Else
// Web application
Logpath = appdomain. currentdomain. basedirectory + @ "Bin" ;
}
Return Logpath;
}
Set {logpath = Value ;}
}

/// <Summary>
/// Write logs
/// </Summary>
/// <Param name = "logfile"> file name, for example, info </param>
/// <Param name = "MSG"> log content </param>
Public Static Void Writelog ( String Logfile, String MSG)
{
Try
{
System. Io. streamwriter Sw = system. Io. file. appendtext (
Logpath + logfile + "" +
Datetime. Now. tostring ( "Yyyymmdd" ) + ". Log"
);
Sw. writeline (datetime. Now. tostring ( "Yyyy-mm-dd hh: mm: SS :" ) + MSG );
Sw. Close ();
}
Catch
{}
}

# Endregion

}
}

 

Create a class myinstaller. CS

 Using System;
Using System. configuration. Install;
Using System. serviceprocess;
Using System. componentmodel;
Namespace Winservice1
{
[Runinstaller ( True )]
Public Partial Class Myinstaller: Installer
{
Private Serviceinstaller sinstall;
Private Serviceprocessinstaller sprocessinstall;
Public Myinstaller ()
{
Sinstall =New Serviceinstaller ();
Sprocessinstall = New Serviceprocessinstaller ();
Sprocessinstall. Account = serviceaccount. LocalSystem;
Sinstall. starttype = servicestartmode. Automatic;
Sinstall. servicename = "Scheduleservice" ; // The service name must be the same as the service name in step 1.
Sinstall. displayname = "Task plan service" ;
Sinstall. Description = "This is the description of the Task Scheduler Service .." ;
Installers. Add (sinstall );
Installers. Add (sprocessinstall );
}
}
}

 

In program. CS

 Using System. serviceprocess;

Namespace Winservice1
{
Static Class Program
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
Static Void Main ()
{
Servicebase [] servicestorun;
Servicestorun = New Servicebase []
{
New Scheduleservice ()
};
Servicebase. Run (servicestorun );

// Switch the current directory of winservice1.exe at runtime (switch the drive letter directly, switch the CD folder)
// Enter F: \ windows \ Microsoft. NET \ framework \ v2.0.50727 \ installutil.exe winservice1.exe
// A new service is displayed in the service.

// In addition, the method for deleting a service is as follows:
// At runtime, set the current directory to the directory where winservice1.exe is located,
// SC Delete myservice (myservice is the name of the service to be deleted) to delete the service
}
}
}

Generate the project, and then

Add a new service to the Management> service according to the notes in program. CS, and then start the service;

Debug> attach to process

Now you can debug the service program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.