検索
ホームページバックエンド開発C#.Net チュートリアルC# は、Windows サービスのスケジュールされたタスクのグラフィックおよびテキスト コード分析を追加します

这篇文章主要为大家详细介绍了C#添加Windows服务,定时任务的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了C#添加Windows服务的具体方法,供大家参考,具体内容如下

步骤一、创建服务项目。

步骤二、添加安装程序。

步骤三、服务属性设置 【serviceInstaller1】。

4.1 添加定时任务

public partial class SapSyn : ServiceBase
 {
 System.Timers.Timer timer1; //计时器
 System.Timers.Timer timer2; //计时器
 System.Timers.Timer timer3; //计时器
 System.Timers.Timer timer4; //计时器
 public SapSyn()
 {
  InitializeComponent();
 }

 protected override void OnStart(string[] args)
 {
  
  timer1 = new System.Timers.Timer();
  timer1.Interval = 8000; //设置计时器事件间隔执行时间
  timer1.Elapsed += new System.Timers.ElapsedEventHandler(TMStart1_Elapsed);
  timer1.Enabled = true;

  timer2 = new System.Timers.Timer();
  timer2.Interval = 8000; //设置计时器事件间隔执行时间
  timer2.Elapsed += new System.Timers.ElapsedEventHandler(TMStart2_Elapsed);
  timer2.Enabled = true;

  timer3 = new System.Timers.Timer();
  timer3.Interval = 8000; //设置计时器事件间隔执行时间
  timer3.Elapsed += new System.Timers.ElapsedEventHandler(TMStart3_Elapsed);
  timer3.Enabled = true;

  timer4 = new System.Timers.Timer();
  timer4.Interval = 8000; //设置计时器事件间隔执行时间
  timer4.Elapsed += new System.Timers.ElapsedEventHandler(TMStart4_Elapsed);
  timer4.Enabled = true;

 }
 
 protected override void OnStop() //服务停止执行
 {
  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()
 {
  //服务暂停执行代码
  base.OnPause();
 }
 protected override void OnContinue()
 {
  //服务恢复执行代码
  base.OnContinue();
 }
 protected override void OnShutdown()
 {
  //系统即将关闭执行代码
  base.OnShutdown();
 }

 
 private void TMStart1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
 { 
  //执行SQL语句或其他操作
  using (System.IO.StreamWriter 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)
 { 
  //执行SQL语句或其他操作
  using (System.IO.StreamWriter 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)
 { 
  //执行SQL语句或其他操作
  using (System.IO.StreamWriter 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)
 { 
  //执行SQL语句或其他操作
  using (System.IO.StreamWriter sw = new System.IO.StreamWriter("C:\\" + 4 + "log.txt", true))
  {
  sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "Start.");
  }
 }



 }

4.2 设置服务启动方式为自动启动

[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)
 {
  //参数为服务的名字
  System.ServiceProcess.ServiceController controller = new System.ServiceProcess.ServiceController("ServiceSapSyn");
  controller.Start();
 }
 private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
 {

 }
 }

步骤五、脚本配置。

安装服务脚本

 代码如下:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe WindowsServiceTest.exeNet Start ServiceTestsc config ServiceTest start= auto

卸载服务脚本

代码如下:

%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe /u WindowsServiceTest.exe


5.1 停止或启动服务的代码

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 = "启动服务";
 }

 /// <summary>
 /// 启动服务
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></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 = "启动服务:你选择的服务已经启动。";
  Cursor = Cursors.Default;
 }

 /// <summary>
 /// 停止服务
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></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 = "启动服务:你选择的服务已经卸载。";
  Cursor = Cursors.Default;
 }

 

 private void button3_Click(object sender, EventArgs e)
 {
  ///选择文件框 对象
  OpenFileDialog ofd = new OpenFileDialog();
  //打开时指定默认路径
  ofd.InitialDirectory = @"C:\Documents and Settings\Administrator.ICBCOA-6E96E6BE\桌面";
  //如果用户点击确定
  if (ofd.ShowDialog() == DialogResult.OK)
  {
  //将用户选择的文件路径 显示 在文本框中
  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();
 }

 

 //读写文本 - 写入数据按钮
 private void buttonWrite_Click(string filePath)
 { 
  
 }


 /// <summary>
 /// 运行CMD命令
 /// </summary>
 /// <param name="cmd">命令</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>
 /// 关闭进程
 /// </summary>
 /// <param name="ProcName">进程名称</param>
 /// <returns></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(); // 当发送关闭窗口命令无效时强行结束进程
   result = true;
  }
  }
  return result;
 }

 }

5.2 Form1.Designer.cs 代码

partial class Form1
 {
 /// <summary>
 /// 必需的设计器变量。 Form1.Designer.cs
 /// </summary>
 private System.ComponentModel.IContainer components = null;

 /// <summary>
 /// 清理所有正在使用的资源。
 /// </summary>
 /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
 protected override void Dispose(bool disposing)
 {
  if (disposing && (components != null))
  {
  components.Dispose();
  }
  base.Dispose(disposing);
 }

 #region Windows 窗体设计器生成的代码

 /// <summary>
 /// 设计器支持所需的方法 - 不要
 /// 使用代码编辑器修改此方法的内容。
 /// </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("微软雅黑", 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 = "启动服务";
  this.button1.UseVisualStyleBackColor = true;
  this.button1.Click += new System.EventHandler(this.button1_Click);
  // 
  // button2
  // 
  this.button2.Font = new System.Drawing.Font("微软雅黑", 12F, System.Drawing.FontStyle.Regular, System.Drawing.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 = "停止服务";
  this.button2.UseVisualStyleBackColor = true;
  this.button2.Click += new System.EventHandler(this.button2_Click);
  // 
  // textBox1
  // 
  this.textBox1.Font = new System.Drawing.Font("微软雅黑", 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("微软雅黑", 10.5F, System.Drawing.FontStyle.Underline, System.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 = "请选择服务路径";
  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 = "选择服务程序";
  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;
 }

以上がC# は、Windows サービスのスケジュールされたタスクのグラフィックおよびテキスト コード分析を追加しますの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
Web、デスクトップ、モバイル開発用のC#.NETWeb、デスクトップ、モバイル開発用のC#.NETApr 25, 2025 am 12:01 AM

C#と.NETは、Web、デスクトップ、モバイル開発に適しています。 1)Web開発では、ASP.Netcoreがクロスプラットフォーム開発をサポートしています。 2)デスクトップ開発では、さまざまなニーズに適したWPFとWINFORMSを使用します。 3)モバイル開発は、Xamarinを介したクロスプラットフォームアプリケーションを実現します。

C#.NETエコシステム:フレームワーク、ライブラリ、およびツールC#.NETエコシステム:フレームワーク、ライブラリ、およびツールApr 24, 2025 am 12:02 AM

C#.NETエコシステムは、開発者がアプリケーションを効率的に構築できるようにするための豊富なフレームワークとライブラリを提供します。 1.ASP.NETCOREは、高性能Webアプリケーションの構築に使用されます。2.EntityFrameWorkCoreは、データベース操作に使用されます。これらのツールの使用とベストプラクティスを理解することにより、開発者はアプリケーションの品質とパフォーマンスを向上させることができます。

azure/awsへのc#.netアプリケーションの展開:ステップバイステップガイドazure/awsへのc#.netアプリケーションの展開:ステップバイステップガイドApr 23, 2025 am 12:06 AM

c#.netアプリをAzureまたはAWSに展開する方法は?答えは、AzureAppServiceとAwselasticBeanStalkを使用することです。 1。Azureでは、AzureAppServiceとAzurePipelinesを使用して展開を自動化します。 2。AWSでは、Amazon ElasticBeanstalkとAwslambdaを使用して、展開とサーバーレス計算を実装します。

C#.NET:強力なプログラミング言語の紹介C#.NET:強力なプログラミング言語の紹介Apr 22, 2025 am 12:04 AM

C#と.NETの組み合わせにより、開発者に強力なプログラミング環境を提供します。 1)C#は、多型と非同期プログラミングをサポートします。2).NETは、クロスプラットフォーム機能と同時処理メカニズムを提供し、デスクトップ、Web、モバイルアプリケーション開発で広く使用されています。

.NETフレームワーク対C#:用語のデコード.NETフレームワーク対C#:用語のデコードApr 21, 2025 am 12:05 AM

.NetFrameworkはソフトウェアフレームワークであり、C#はプログラミング言語です。 1..netframeworkは、デスクトップ、Web、モバイルアプリケーションの開発をサポートするライブラリとサービスを提供します。 2.C#は.NetFrameWork用に設計されており、最新のプログラミング機能をサポートしています。 3..NetFrameworkはCLRを介してコード実行を管理し、C#コードはILにコンパイルされ、CLRによって実行されます。 4. .NetFrameWorkを使用してアプリケーションをすばやく開発し、C#はLINQなどの高度な関数を提供します。 5.一般的なエラーには、タイプ変換と非同期プログラミングデッドロックが含まれます。 VisualStudioツールは、デバッグに必要です。

C#.NETの分解:初心者の概要C#.NETの分解:初心者の概要Apr 20, 2025 am 12:11 AM

C#は、Microsoftが開発した最新のオブジェクト指向プログラミング言語であり、.NETはMicrosoftが提供する開発フレームワークです。 C#は、CのパフォーマンスとJavaのシンプルさを組み合わせており、さまざまなアプリケーションの構築に適しています。 .NETフレームワークは、複数の言語をサポートし、ガベージコレクションメカニズムを提供し、メモリ管理を簡素化します。

C#と.NETランタイム:それらがどのように連携するかC#と.NETランタイム:それらがどのように連携するかApr 19, 2025 am 12:04 AM

C#と.NETランタイムは密接に連携して、開発者に効率的で強力なプラットフォームの開発機能に力を与えます。 1)C#は、.NETフレームワークとシームレスに統合するように設計されたタイプセーフおよびオブジェクト指向のプログラミング言語です。 2).NETランタイムは、C#コードの実行を管理し、ガベージコレクション、タイプの安全性、その他のサービスを提供し、効率的でクロスプラットフォームの操作を保証します。

C#.NET開発:始めるための初心者向けガイドC#.NET開発:始めるための初心者向けガイドApr 18, 2025 am 12:17 AM

C#.NET開発を開始するには、次のことが必要です。1。C#の基本的な知識と.NETフレームワークのコア概念を理解する。 2。変数、データ型、制御構造、関数、クラスの基本概念をマスターします。 3。LINQや非同期プログラミングなど、C#の高度な機能を学習します。 4.一般的なエラーのためのデバッグテクニックとパフォーマンス最適化方法に精通してください。これらの手順を使用すると、C#.NETの世界に徐々に浸透し、効率的なアプリケーションを書き込むことができます。

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

PhpStorm Mac バージョン

PhpStorm Mac バージョン

最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

mPDF

mPDF

mPDF は、UTF-8 でエンコードされた HTML から PDF ファイルを生成できる PHP ライブラリです。オリジナルの作者である Ian Back は、Web サイトから「オンザフライ」で PDF ファイルを出力し、さまざまな言語を処理するために mPDF を作成しました。 HTML2FPDF などのオリジナルのスクリプトよりも遅く、Unicode フォントを使用すると生成されるファイルが大きくなりますが、CSS スタイルなどをサポートし、多くの機能強化が施されています。 RTL (アラビア語とヘブライ語) や CJK (中国語、日本語、韓国語) を含むほぼすべての言語をサポートします。ネストされたブロックレベル要素 (P、DIV など) をサポートします。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。