C # create a Windows Service (Windows Services) and restart the Service regularly

Source: Internet
Author: User

//Author: Liu yongfaWww.yongfa365.com

Using system;

Using system. Collections. Generic;

Using system. componentmodel;

Using system. Data;

Using system. diagnostics;

Using system. serviceprocess;

Using system. IO;

Using system. text;

Using system. Timers;

 

 

Namespace cbdcn_reboot

{

Public partial class service1: servicebase

{

Public service1 ()

{

Initializecomponent ();

}

 

Protected override void onstart (string [] ARGs)

{

// Todo:AddCodeTo start the service.

Double sleeptime = validatordate1 (system. datetime. now. tostring ("yyy-mm-dd hh: mm: SS"), system. datetime. now. tostring ("yyy-mm-dd") + "07:00:00 ");

If (sleeptime <0) sleeptime + = 24x60x60*1000;

Writestr ("Start", Sleeptime );

System. Timers. Timer T = new system. Timers. Timer (sleeptime );//InstantiationTimerClass, set the interval10000Millisecond;

T. elapsed + = new system. Timers. elapsedeventhandler (rebootsystem );//Execute the event at the time of arrival;

T. autoreset = true ;//The setting is executed once (False) Or keep running(True);

T. Enabled = true ;//Execute?System. Timers. Timer. elapsedEvent;

Writestr ("End", Sleeptime );

}

Public void rebootsystem (Object source, system. Timers. elapsedeventargs E)

{

System. Diagnostics. process. Start ("shutdown", "/R/F/T 0 ");

}

 

Public static double validatordate1 (string strdatea, string strdateb)

{

String strfrom = strdateb;

String strto = strdatea;

Timespan Ts = convert. todatetime (strfrom)-convert. todatetime (strto );

Double COUNT = ts. totalsecondds * 1000;

Return count;

}

 

 

 Public void writestr (string README, double sleeptime)

{

// Debug ============================================ ==================

Streamwriter dout = new streamwriter (@ "C: \" + system. datetime. Now. tostring ("yyymmddhhmmss") + readme + ". txt ");

Dout. Write ("\ nsleeptime:"+ Convert. tostring (sleeptime) +" \ nOperation Time:"+ System. datetime. Now. tostring (" yyy-mm-dd hh: mm: SS "));

// Debug ============================================ ==================

Dout. Close ();

}

 

Protected override void onstop ()

{

 

}

}

}

 

 

Online Introduction

 

UseC #CreateWindowsService(Windows Services)

WindowsService inVisual StudioIn previous versionsNTService, inVs.netA new name is enabled. UseVisual C #CreateWindowsService is not a difficult task, this article will guide you step by step to createWindowsService and use it. When the service starts and stops, it writes some text information to a text file. 

Step 1: create a service framework

To create a newWindowsService, fromVisual C #Select from projectWindowsService (Windows Service) Option, give the project a new file name, and then click OK. 

You can see that the wizard addsWebservice1.csClass: 

 The meaning of each attribute is:

 

 AutologWhether to automatically write log files to the System 

 

 CanhandlepowereventReceive Power Events during service 

 

 CanpauseandcontinueWhether the Service accepts the request to suspend or continue running 

 

 CanshutdownWhether the Service receives a notification when the computer that runs it is disabled so that it can callOnshutdownProcess 

 

 CanstopWhether the Service accepts the stop operation request 

 

 ServicenameService name 

 

 

 

Step 2: add features to the service

Add a headerUsing system. IO;

In. CSIn the code file, we can see that there are two ignored functions.OnstartAndOnstop.

 

OnstartThe function is executed when the service is started,OnstopThe function is executed when the service is stopped. Here, when the service is started and stopped, some text information is written to a text file. The Code is as follows::

 

Protected override void onstart (string [] ARGs)

{

 // Todo:Add code here to start the service. 

 Filestream FS = new filestream (@ "D: \ mcwindowsservice.txt", filemode. openorcreate, fileaccess. Write );

 

 Streamwriter m_streamwriter = new streamwriter (FS );

 

 M_streamwriter.basestream.seek (0, seekorigin. End );

 

 M_streamwriter.writeline ("mcwindowsservice: Service started" + datetime. Now. tostring () + "\ n ");

 

 M_streamwriter.flush ();

 

 M_streamwriter.close ();

 

 FS. Close ();

}

 

Protected override void onstop ()

{

 // Todo:Add code here to stop the service. 

 Filestream FS = new filestream (@ "D: \ mcwindowsservice.txt", filemode. openorcreate, fileaccess. Write );

 

 Streamwriter m_streamwriter = new streamwriter (FS );

 

 M_streamwriter.basestream.seek (0, seekorigin. End );

 

 M_streamwriter.writeline ("mcwindowsservice: Service stopped" + datetime. Now. tostring () + "\ n ");

 

 M_streamwriter.flush ();

 

 M_streamwriter.close ();

 

 FS. Close ();

}

 

 Step 3:InstallProgramAdd to service application 

 

 Visual Studio. NETTogether with the installation component, you can install the resources associated with the service application. The installation component registers a single service on the system to which it is being installed, and notifies the Service Control Manager of the existence of the service. 

 

To correctly install the service, you do not need to perform any special encoding in the installer. However, to add special features to the installation process, you may occasionally need to modify the content of the installation program. 

 

 To add an installer to a service application, follow these steps::

 

1: In the solution, access the service to which you want to add and install componentsDesignView. 

 

2: In the Properties window, click"Add installer"Link,If no, right-click the gray help area under the property, select "command", and"Add installer"The link is displayed. 

 

 A new class is added to the project.ProjectinstallerAnd two installation componentsServiceprocessinstallerAndServiceinstallerAnd the service property value is copied to the component.

 

3: To determine how to start the service, clickServiceinstallerComponent andStarttypeSet the property to an appropriate value. 

 

 ManualAfter the service is installed, you must start it manually. 

 

 AutomaticThe service is automatically started every time the computer restarts. 

 

 DisabledThe service cannot be started. 

 

4: SetServiceprocessinstallerClassAccountAttribute changedLocalSystem

 

 In this way, no matter which user is logged on to the system, the service will always start. 

 

 

 

Step 4: generate a service program 

You can select generate from the generate menu to generate a project. 

 

Note:Do not pressF5Key to run the project -- the service project cannot be run in this way. 

 

Step 5: Install the service 

 

Access the directory of compiled executable files in the project.

Use the project output as a parameter to run from the command lineInstallutil.exe. Enter the following code in the command line:

Installutil yourproject.exe

 

Note:Installutil.exeThere are two editions available on my machine: 

C: \ windows \ Microsoft. NET \ framework \ v1.1.4322 \ installutil.exe16 KUsed. Net1.1

C: \ windows \ Microsoft. NET \ framework \ v2.0.50727 \ installutil.exe26 KUsed. Net2.0

 

 

Uninstall Service

 

Use the project output as a parameter to run from the command lineInstallutil.exe.

 

Installutil/u yourproject.exe

 

If the file is changed to a folder, an error may occur when it is run again. You canCMDInput:SC DeleteService name. Delete the service.

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.