通過.NET平台編寫和發布簡單的Windows Service

來源:互聯網
上載者:User

建立一個(VB.NET/C#)項目,選擇Windows Service應用..然後在OnStart類裡就可以添加代碼了.
  如果想實現定時運行,活即時監聽的功能,可以用.NET 提供的TIMER類.
  以下是程式碼片段.
   private void theTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
  {

  if (!ExCondition())

  { return;

  }

  try

  {

  theTimer.Enabled = false;

  MyTransaction();

  }

  catch(Exception es)

  {

  WriteLog(es.Message);

  }

  theTimer.Enabled = true;

  }

  //檢測執行條件

  private bool ExCondition()

  {

  DateTime dtNow = DateTime.Now;

  if(this.currentmode.Equals("auto"))

  {

  string[] frev = this.freqvalue.Split('-');

  switch( this.freq)

  {

  case "2"://2-每小時

  if( (dtNow.Minute == 59)&(dtNow.Second< 30))

  {

  return true;

  }

  break;

  case "4"://4-每天,

  if((dtNow.Hour == int.Parse(frev[1]))&(dtNow.Minute == int.Parse(frev[2]))&(dtNow.Second<30))

  {

  return true;

  }

  break;

  case "8"://8-每周,

  int we = int.Parse(frev[0].Substring(1,1));

  if((dtNow.DayOfWeek.ToString().Equals(Week[we]))&(dtNow.Hour == int.Parse(frev[1]))&(dtNow.Minute == int.Parse(frev[2]))&(dtNow.Second<30))

  {

  return true;

  }

  break;

  case "16"://16-每月,

  int mm = int.Parse(frev[0].Substring(1,frev[0].Length-1));

  if((dtNow.Day == mm)&(dtNow.Hour == int.Parse(frev[1]))&(dtNow.Minute == int.Parse(frev[2]))&(dtNow.Second<30))

  {

  return true;

  }

  break;

  default://無觸發

  return true;

  break;
  }

  }

  else

  {

  switch(this.startpoint)

  {

  case "0":

  return true;

  break;

  default:

  string[] st = startpoint.Split('-');

  if((dtNow.Hour == int.Parse(st[0]))&(dtNow.Minute ==int.Parse(st[1]))&(dtNow.Second<30))

  {

  return true;

  }

  break;

  }

  }

  return false;

  }

  註冊你的Windows Service程式.

  用InstallUtil IASserver.exe (這個檔案預設在C:/WINNT/Microsoft.NET/Framework/v1.1.4322下)

  InstallUtil IASserver.exe

  InstallUtil IASserver.exe /u (卸載)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.