2012-05-08 2 views
1

아무도 모르게 컴퓨터의 배경에서 항상 Windows 서비스를 실행하려고합니다. 내 Windows 서비스는 내 전자 메일받은 편지함의 내용을 다운로드하여 내 데이터베이스에 저장합니다.Windows 서비스를 계속 실행하려면 어떻게합니까?

내 Windows 서비스가 멈추기 만하면됩니다 - 60 초마다 로그를 입력 한 다음 약 10 분 동안 멈 춥니 다.

아래 코드를 게시했습니다. 아무도 이유를 보거나 말할 수 있습니까?

도움을 주시면 감사하겠습니다.

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Diagnostics; 
using System.Linq; 
using System.ServiceProcess; 
using System.Text; 
using System.Timers; 

namespace EmailWindowsService 
{ 
    public partial class MyEmailService : ServiceBase 
    { 
     private DateTime lastRun; 
     private bool flag = true; 
     private static System.Timers.Timer aTimer; 
     public MyEmailService() 
     { 
      InitializeComponent(); 
      if (!System.Diagnostics.EventLog.SourceExists("MySource")) // every thing the windows service does is logged in server explorer 
      { 
       System.Diagnostics.EventLog.CreateEventSource(
        "MySource", "MyNewLog"); 
      } 
      eventLogEmail.Source = "MySource"; 
      eventLogEmail.Log = "MyNewLog"; 

      // Timer Code 
      aTimer = new System.Timers.Timer(1 * 60 * 1000); // 60 seconds 
      aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
      aTimer.Enabled = true; 
      // Timer Code 
     } 

     protected override void OnStart(string[] args) 
     { 
      flag = true; 
      lastRun = DateTime.Now; 
      eventLogEmail.WriteEntry("Started"); 
     } 

     protected override void OnStop() 
     { 
      eventLogEmail.WriteEntry("Stopped"); 
     } 
     protected override void OnPause() 
     { 
      eventLogEmail.WriteEntry("Paused"); 
     } 
     protected override void OnContinue() 
     {  
      eventLogEmail.WriteEntry("Continuing"); 
     } 
     protected override void OnShutdown() 
     { 
      eventLogEmail.WriteEntry("ShutDowned"); 
     } 

     private void OnTimedEvent(object source, ElapsedEventArgs e) 
     { 
      RetriveEmailClass Emails = new RetriveEmailClass(); 
      if (flag == true) 
      { 
       eventLogEmail.WriteEntry("In getting Email Method"); 
       Emails.ServiceEmailMethod(); 
       lastRun = DateTime.Now; 
       flag = false; 
      } 
      else if (flag == false) 
      { 
       if (lastRun.Date < DateTime.Now.Date) 
       { 
        Emails.ServiceEmailMethod(); 
        eventLogEmail.WriteEntry("In getting Email Method"); 
       } 
      } 
     }  
     } 
    } 
+1

Windows 서비스가 예기치 않게 중지되는 이유는 다음과 같습니다. 1) 처리되지 않은 예외 2) 누군가 종료되었습니다. 이제 코드에 예외 처리를 추가하고 오류의 위치를 ​​확인하십시오. – Shai

+0

멈추는 이유를 디버깅하기 위해 코드에'try-catch'를 넣으십시오. –

+1

내가 틀렸다면 미안하지만 이전에 비슷한 질문을 한 적이 있습니까? 당신은 [Pomster] (http://stackoverflow.com/users/1356321/pomster)입니까? 그런 다음 새 계정을 만드는 이유는 무엇입니까? 다른 질문의 맥락에서 질문을 볼 수 있다면 쉽게 도움이됩니다. 내가 틀렸다면 사과드립니다. – Skalli

답변

0

클래스에 오류가 없는지 확인하십시오. 오류로 인해 전체 서비스가 중단 될 수 있습니다. 또한 타이머를 메서드에 넣고 서비스 코드에만 넣지 말고 호출하십시오.

Windows 서비스는 항상 호출 할 메서드가있는 빈 셸로 만들어야합니다.

+1

http://stackoverflow.com/users/1356321/pomster – Pomster

0

코드는 Emails.ServiceEmailMethod 메소드의 소스를 제외하고는 간단합니다. 이 메서드는 예외를 생성합니까? 그렇다면 귀하의 타이머 방식에 갇혀 있지 않습니다. 시도하십시오 :

try { Emails.ServiceEmailMethod(); } 
catch (Exception ex) { eventLogEmail.WriteEntry(ex.Message); } 
0

Windows 서비스가 중지되는 몇 가지 이유가 있습니다.

1. Unhandled exception in your code. Looking from you code snippet, please add exception handling in the OnTimedEvent() method. 
2. You service may crashed for some reason. In this case, you can go to event viewer to find out the reason for the failure. 

희망이 도움이됩니다.

0

대부분 처리되지 않은 예외가 있습니다. System.Timers.Timer을 사용했기 때문에 숨겨져 있습니다. 이 타이머는 앱을 중단시키지 않고 모든 처리되지 않은 예외를 처리합니다.

즉, 앱이 정상적으로 실행되고있는 것처럼 보일 수 있습니다. 타이머 콜백에서 try/catch가이를 증명할 것입니다.

그런 식으로 작동하지 않으므로 대신 System.Threading.Timer을 사용하는 것이 좋습니다.

관련 문제