Scheduled operation of Windows service programs [reprinted]

Source: Internet
Author: User

Create a Windows Service Program for scheduled operations
Posted on author reading (692) Comments (9) EDIT favorites
In project development, we may need to execute some pre-defined tasks by the system at intervals, for example, we can check the system for emails to be sent at every interval and monitor file operations at any time by creating a Windows service program, for more information about Windows service programs, see this article: Use Visual C # To create a Windows service program. After reading this article, I have practiced it myself. Now I will record my operation steps as follows:
1. Create a Windows project and select a "Windows Service" project.

2. The generated program. CS file defines the main function of service startup.

Code
Namespace windowsservice1
{
Static class Program
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
Static void main ()
{
Servicebase [] servicestorun;
Servicestorun = new servicebase []
{
New service1 ()
};
Servicebase. Run (servicestorun );
}
}
}

3. In the new project, click the service1.cs file to switch to the Code view. The generated code inherits from the servicebase base class and the onstart and onstop methods are reloaded. I made some simple operations in this file, that is, defining a timer at the beginning of the service, and then writing the current time to the file every other second.

Code
Namespace windowsservice1
{
Public partial class service1: servicebase
{
Timer timer;
Public service1 ()
{
Initializecomponent ();
}

Protected override void onstart (string [] ARGs)
{
Timer = new timer (1000 );
Timer. elapsed + = new elapsedeventhandler (timer_elapsed );
Timer. Start ();
}

Protected override void onstop ()
{
Timer. Stop ();
Timer. Dispose ();
}

Void timer_elapsed (Object sender, elapsedeventargs E)
{
String filepath = appdomain. currentdomain. basedirectory + "test.txt ";
Streamwriter Sw = NULL;
If (! File. exists (filepath ))
{
Sw = file. createtext (filepath );
}
Else
{
Sw = file. appendtext (filepath );
}
Sw. Write ("Access time:" + datetime. Now. tostring () + environment. newline );
Sw. Close ();
}
}
}
4. Add an installer class to the project.

4. In the newly added installer class, set the service name, startup method, account name, and password.

Code
Namespace windowsservice1
{
Partial class installer1
{
/// <Summary>
/// Required designer variables.
/// </Summary>
Private system. componentmodel. icontainer components = NULL;

Private system. serviceprocess. serviceprocessinstaller spinstaller;
Private system. serviceprocess. serviceinstaller sinstaller;

/// <Summary>
/// Clear all resources in use.
/// </Summary>
/// <Param name = "disposing"> If the managed resource should be released, the value is true; otherwise, the value is false. </Param>
Protected override void dispose (bool disposing)
{
If (disposing & (components! = NULL ))
{
Components. Dispose ();
}
Base. Dispose (disposing );
}

# Code generated by the region component designer

/// <Summary>
/// The designer supports the required methods-do not
/// Use the code editor to modify the content of this method.
/// </Summary>
Private void initializecomponent ()
{
Components = new system. componentmodel. Container ();

// Create the serviceprocessinstaller object and serviceinstaller object
This. spinstaller = new system. serviceprocess. serviceprocessinstaller ();
This. sinstaller = new system. serviceprocess. serviceinstaller ();

// Set the account, user name, and password of the serviceprocessinstaller object
This. spinstaller. Account = system. serviceprocess. serviceaccount. LocalSystem;
This. spinstaller. Password = NULL;
This. spinstaller. Username = NULL;

// Set the service name
This. sinstaller. servicename = "windowsservice1 ";

// Set the Service Startup Method
This. sinstaller. starttype = system. serviceprocess. servicestartmode. Automatic;

This. installers. addrange (new system. configuration. Install. installer [] {
This. spinstaller, this. sinstaller });
}

# Endregion
}
}
5. Generate the project. The EXE file is generated in the bin directory. In the scripts directory, I installed vs 2010, and the corresponding directory is: C: \ WINDOWS \ Microsoft. net \ framework \ v4.0.30319 \ installutil.exe, and then the directory of the installutil.exe + EXE file to be executed, such as installutil.exe F: \ myproject \ windowsservice1 \ windowsservice1 \ bin \ debug \ windowsservice1.exe. After successful execution, the name of the added service appears in the Windows service.

6. Start the service. Open the bin \ debug folder and find that a file named test.txt has been generated, which records the time. This indicates that the service has been officially started.
7. it is easy to stop the service. Open the command line tool and go to c: \ windows \ Microsoft. run the installutil.exe-u F: \ myproject \ windowsservice1 \ windowsservice1 \ bin \ debug \ windowsservice1.exe command.
Download source code: Create a Windows Service Program
Category: ASP. NET

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.