2016-03-28 42 views
0

我試圖在.NET中使用TopShelf和FluentScheduler在windows服務中每隔10秒觸發一個事件,但我不僅僅是每10秒觸發一次事件。我分享我的實施,請引導我。FluentScheduler無法正常工作

class Program 
    {   
     static void Main(string[] args) 
     { 
      HostFactory.Run(x => 
      { 
       x.Service<IWindowsService>(s => 
       { 
        s.ConstructUsing(name => new WindowsService(new SchedulerRegistry(new Worker()))); 
        s.WhenStarted(tc => tc.Start()); 
        s.WhenStopped(tc => tc.Stop()); 
       }); 

       x.RunAsLocalSystem(); 

       x.SetDescription("Test"); 
       x.SetDisplayName("Test Service"); 
       x.SetServiceName("Testservice"); 

       x.StartAutomatically(); 

       x.EnableServiceRecovery(s => 
       { 
        s.RestartService(1); 
        s.RestartService(2); 
       }); 
      }); 
     } 
    } 

    public class SchedulerRegistry : Registry 
    { 
     public SchedulerRegistry(Worker worker) 
     { 
      Schedule(() => 
      { 
       try 
       { 
        worker.Run(); 
       } 
       catch (Exception ex) 
       { 

        throw; 
       } 
      }).NonReentrant().ToRunNow().AndEvery(10).Seconds(); 
     } 
    } 

    public interface IWindowsService 
    { 
     void Start(); 
     void Stop(); 
    } 

    public class WindowsService : IWindowsService 
    { 
     public WindowsService(SchedulerRegistry registry) 
     { 
      JobManager.Initialize(registry); 
     } 

     public void Start() 
     { 
      Console.WriteLine("Service started"); 
     } 

     public void Stop() 
     { 
      Console.WriteLine("Service stopped"); 
     } 
    } 

    public class Worker 
    { 
     public void Run() 
     { 
      CheckUrl(); 
     } 

     public static void CheckUrl() 
     { 
      HttpWebResponse response = null; 

      try 
      { 
       HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://google.com"); 
       request.Method = "GET"; 

       response = (HttpWebResponse)request.GetResponse(); 

       if (response.StatusCode == HttpStatusCode.OK) 
       { 
       } 
       else 
       { 
       } 
      } 
      catch (WebException e) 
      { 
       response.Close(); 
      } 
      finally 
      { 
       if (response != null) 
       { 
        response.Close(); 
       } 
      } 
     } 

    } 
+0

這不是一個答案,但你可能想嘗試Hangfire(http://hangfire.io),它可以做調度和更多;它有相當廣泛的用戶基礎和良好的文檔。 –

+0

它是否發射? –

+0

@ColeW一點都沒有 – Anony

回答

0

我能得到它做對運行以下命令:

public class WindowsService : IWindowsService 
{ 
    private SchedulerRegistry registry; 

    public WindowsService(SchedulerRegistry schedulerRegistry) 
    { 
     this.registry = schedulerRegistry; 
    } 

    public void Start() 
    { 
     Console.WriteLine("Service started"); 

     JobManager.Initialize(this.registry); 
    } 

    public void Stop() 
    { 
     Console.WriteLine("Service stopped"); 
    } 
} 

基本上我所做的只是改變JobManager.Initialize(this.registry)是被稱爲地方。我不認爲你希望它運行,直到你的服務開始,所以我認爲這是有道理的。