C # Add graphical code parsing for Windows service timer tasks

Source: Internet
Author: User
This article mainly for you in detail the C # Add Windows services, scheduled tasks related materials, with a certain reference value, interested in small partners can refer to

The example of this article for everyone to share the C # Add Windows Services specific methods for your reference, the specific content is as follows

Step One, create a service project.

Step Two, add the installation program.

step Three, the service properties set "ServiceInstaller1".

4.1 Adding a scheduled task

Public partial class Sapsyn:servicebase {System.Timers.Timer timer1;//Timer System.Timers.Timer timer2;//Timer System.tim ERs. Timer Timer3; Timer System.Timers.Timer timer4; Timer public Sapsyn () {InitializeComponent ();} protected override void OnStart (string[] args) {timer1 = new System.  Timers.timer (); Timer1. Interval = 8000; Sets the timer event interval execution time timer1.  Elapsed + = new System.Timers.ElapsedEventHandler (tmstart1_elapsed); Timer1.  Enabled = true;  Timer2 = new System.Timers.Timer (); Timer2. Interval = 8000; Sets the timer event interval execution time timer2.  Elapsed + = new System.Timers.ElapsedEventHandler (tmstart2_elapsed); Timer2.  Enabled = true;  Timer3 = new System.Timers.Timer (); Timer3. Interval = 8000; Sets the timer event interval execution time Timer3.  Elapsed + = new System.Timers.ElapsedEventHandler (tmstart3_elapsed); Timer3.  Enabled = true;  Timer4 = new System.Timers.Timer (); Timer4. Interval = 8000; Sets the timer event interval execution time timer4.  Elapsed + = new System.Timers.ElapsedEventHandler (tmstart4_elapsed); Timer4. Enabled = true; } protectedoverride void OnStop ()//service Stop execution {using (System.IO.StreamWriter SW = new System.IO.StreamWriter ("C:\\log.txt", true)) { Sw.  WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + "Stop.");  this.timer1.Enabled = false;  this.timer2.Enabled = false;    this.timer3.Enabled = false; this.timer4.Enabled = false; } protected override void OnPause () {//Service paused execution code base. OnPause (); } protected override void OnContinue () {//Service recovery execution code base. OnContinue (); } protected override void OnShutdown () {//system will close execution code base. OnShutdown (); } private void Tmstart1_elapsed (object sender, System.Timers.ElapsedEventArgs e) {//Execute SQL statement or other operation using (SYSTEM.IO.STR eamwriter SW = new System.IO.StreamWriter ("c:\\" + 1 + "Log.txt", True)) {SW. WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + "Start.");}} private void Tmstart2_elapsed (object sender, System.Timers.ElapsedEventArgs e) {//Execute SQL statement or other operation using (System.IO.Stream Writer SW = new System.IO.StreamWriter ("c:\\" + 2 + "Log.txt", True)) {SW. WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + "Start.");}} private void Tmstart3_elapsed (object sender, System.Timers.ElapsedEventArgs e) {//Execute SQL statement or other operation using (System.IO.Stream Writer SW = new System.IO.StreamWriter ("c:\\" + 3 + "Log.txt", True)) {SW. WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + "Start.");}} private void Tmstart4_elapsed (object sender, System.Timers.ElapsedEventArgs e) {//Execute SQL statement or other operation using (System.IO.Stream Writer SW = new System.IO.StreamWriter ("c:\\" + 4 + "Log.txt", True)) {SW. WriteLine (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + "Start.");}}

4.2 Set service startup mode to start automatically

[Runinstaller (true)] public partial class ProjectInstaller:System.Configuration.Install.Installer {public  ProjectInstaller () {  InitializeComponent ();  this.committed + = new Installeventhandler (projectinstaller_committed); } private void Projectinstaller_committed (object sender, Installeventargs e) {  //parameter is the name  of the service System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController ("Servicesapsyn");  Controller. Start (); private void Serviceinstaller1_afterinstall (object sender, Installeventargs e) {}}

Step Five, script configuration.

Install the service script

The code is as follows:

%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe windowsservicetest.exenet Start SERVICETESTSC Config servicetest start= Auto

Uninstalling the service script

The code is as follows:

%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe/u WindowsServiceTest.exe


5.1 Code to stop or start the service

Public partial class Form1:form {public Form1 () {InitializeComponent ();}  public string thispath = Application.startuppath;  public string propath = ""; private void Form1_Load (object sender, EventArgs e) {this. Text = "Start Service"; }///<summary>//<param name= "sender" ></param>///<param name= "E" &G  t;</param> private void Button1_Click (object sender, EventArgs e) {Cursor = Cursors.waitcursor;  String Starpath = @ "%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe" + propath;  FileStream fs = new FileStream (Thispath + "\\Install.bat", FileMode.Create);  StreamWriter SW = new StreamWriter (FS); try {sw.  WriteLine (Starpath); Sw.  WriteLine ("Net Start servicetest"); Sw.  WriteLine ("sc config servicetest start= auto"); } catch (Exception ex) {MessageBox.Show (ex.  Message.tostring ()); } finally {SW.  Close (); Fs.  Close ();  } System.Diagnostics.Process.Start (Thispath + "\\Install.bat"); This. Text = "Start service: you chooseThe service has been started.  "; Cursor = Cursors.Default; }//<summary>//Stop service///</summary>//<param name= "sender" ></param>//<param name= "E" &G  t;</param> private void Button2_Click (object sender, EventArgs e) {Cursor = Cursors.waitcursor;  String Starpath = @ "%systemroot%\microsoft.net\framework\v4.0.30319\installutil.exe/u" + propath;  FileStream fs = new FileStream (Thispath + "\\Uninstall.bat", FileMode.Create);  StreamWriter SW = new StreamWriter (FS); try {sw.   WriteLine (Starpath); } catch (Exception ex) {MessageBox.Show (ex.  Message.tostring ()); } finally {SW.  Close (); Fs.  Close ();  } System.Diagnostics.Process.Start (Thispath + "\\Uninstall.bat"); This. Text = "Start service: The service you have selected has been uninstalled."  "; Cursor = Cursors.Default;  } private void Button3_Click (object sender, EventArgs e) {///Select File Box object OpenFileDialog ofd = new OpenFileDialog (); Specifies the default path OFD when opened.  InitialDirectory = @ "C:\Documents and settings\administrator.icbcoa-6e96e6be\ desktop"; If the user clicks OK if (ofd. ShoWdialog () = = DialogResult.OK) {//The file path selected by the user is displayed in the text box TextBox1.Text = ofd.  FileName;  Propath = TextBox1.Text;  } if (file.exists (Thispath + "\\Uninstall.bat")) {File.delete (Thispath + "\\Uninstall.bat"); } file.create (Thispath + "\\Uninstall.bat").  Close ();  if (file.exists (Thispath + "\\Install.bat")) {File.delete (Thispath + "\\Install.bat"); } file.create (Thispath + "\\Install.bat"). Close (); }//Read/write text-write Data button private void Buttonwrite_click (String filePath) {}///<summary>//Run cmd command///</summary >//<param name= "cmd" > Command </param>//<returns></returns> public static string cmd (string[]  CMD) {Process p = new process ();  p.StartInfo.FileName = "cmd.exe";  P.startinfo.useshellexecute = false;  P.startinfo.redirectstandardinput = true;  P.startinfo.redirectstandardoutput = true;  P.startinfo.redirectstandarderror = true;  P.startinfo.createnowindow = true;  P.start ();  P.standardinput.autoflush = true; for (int i = 0; i < cmd. Length; i++) {p.standardinput.writeline (Cmd[i].  ToString ());  } p.standardinput.writeline ("Exit");  String strrst = P.standardoutput.readtoend ();  p.WaitForExit ();  P.close (); return strrst; }//<summary>///close process///</summary>//<param name= "procname" > Process name </param>//&LT;RETURNS&G  t;</returns> public static bool Closeprocess (string procname) {bool result = false;  System.Collections.ArrayList proclist = new System.Collections.ArrayList ();  String tempname = "";  int begpos;  int endpos; foreach (System.Diagnostics.Process thisproc in System.Diagnostics.Process.GetProcesses ()) {tempname =  Thisproc.tostring ();  Begpos = Tempname.indexof ("(") + 1;  Endpos = Tempname.indexof (")");  Tempname = tempname.substring (Begpos, Endpos-begpos);  Proclist.add (Tempname);  if (tempname = = procname) {if (!thisproc.closemainwindow ()) Thisproc.kill ();//When the Send close Window command is invalid, force end process result = true; }} return result; } }

5.2 Form1.Designer.cs Code

Partial class Form1 {//<summary>////Required designer variables. Form1.Designer.cs//</summary> private System.ComponentModel.IContainer components = null; <summary>///clean up all resources in use. </summary>//<param name= "disposing" > True if the managed resource should be released, otherwise false. </param> protected override void Dispose (bool disposing) {if (disposing && (components = null)) {compo Nents.  Dispose (); } base. Dispose (disposing); #region the code generated by the Windows Forms Designer///<summary>///designer supports the required method-do not///Use the Code Editor to modify the contents of this method. </summary> private void InitializeComponent () {System.ComponentModel.ComponentResourceManager resources =  New System.ComponentModel.ComponentResourceManager (typeof (Form1));  This.button1 = new System.Windows.Forms.Button ();  This.button2 = new System.Windows.Forms.Button ();  This.textbox1 = new System.Windows.Forms.TextBox ();  This.button3 = new System.Windows.Forms.Button (); This.  SuspendLayout (); Button1//This.button1.Font = new System.Drawing.font ("Microsoft Jas Black", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte) (134)));  This.button1.Location = new System.Drawing.Point (12, 90);  This.button1.Name = "Button1";  This.button1.Size = new System.Drawing.Size (134, 60);  This.button1.TabIndex = 0;  This.button1.Text = "Start Service";  This.button1.UseVisualStyleBackColor = true;  This.button1.Click + = new System.EventHandler (This.button1_click); Button2//This.button2.Font = new System.Drawing.Font ("Microsoft Jas Black", 12F, System.Drawing.FontStyle.Regular, system.dr Awing.  Graphicsunit.point, ((byte) (134)));  This.button2.Location = new System.Drawing.Point (280, 90);  This.button2.Name = "Button2";  This.button2.Size = new System.Drawing.Size (134, 60);  This.button2.TabIndex = 0;  This.button2.Text = "Stop Service";  This.button2.UseVisualStyleBackColor = true;  This.button2.Click + = new System.EventHandler (This.button2_click); TextBox1//This.textBox1.Font = new System.Drawing.Font ("Microsoft Jas Black", 10.5F, SysteM.drawing.fontstyle.regular, System.Drawing.GraphicsUnit.Point, ((byte) (134));  This.textBox1.ForeColor = System.Drawing.Color.Maroon;  This.textBox1.Location = new System.Drawing.Point (108, 13);  This.textBox1.Multiline = true;  This.textBox1.Name = "TextBox1";  This.textBox1.Size = new System.Drawing.Size (306, 67);  This.textBox1.TabIndex = 2; Button3//This.button3.Font = new System.Drawing.Font ("Microsoft Jas Black", 10.5F, System.Drawing.FontStyle.Underline, Syste  M.drawing.graphicsunit.point, ((byte) (134)));  This.button3.ForeColor = System.Drawing.Color.Blue;  This.button3.Location = new System.Drawing.Point (12, 12);  This.button3.Name = "Button3";  This.button3.Size = new System.Drawing.Size (90, 68);  This.button3.TabIndex = 3;  This.button3.Text = "Please select a service path";  This.button3.UseVisualStyleBackColor = true;  This.button3.Click + = new System.EventHandler (This.button3_click); Form1//this.  Autoscaledimensions = new System.Drawing.SizeF (6F, 12F); This. AutoScaleMode = SysteM.windows.forms.autoscalemode.font; This.  ClientSize = new System.Drawing.Size (419, 155); This.  Controls.Add (This.button3); This.  Controls.Add (This.textbox1); This.  Controls.Add (This.button2); This.  Controls.Add (This.button1); This. Icon = ((System.Drawing.Icon) (resources. GetObject ("$this.  Icon ")); This.  Name = "Form1"; This.  Text = "Select Service Program"; This. Load + = new System.EventHandler (this.  Form1_Load); This.  ResumeLayout (FALSE); This. PerformLayout (); } #endregion private System.Windows.Forms.Button button1; Private System.Windows.Forms.Button button2; Private System.Windows.Forms.TextBox TextBox1; Private System.Windows.Forms.Button Button3; }
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.