2014-11-14 39 views
0

我有一個服務,我想運行每X分鐘使用(例如)一個計時器。重新運行的服務每x分鐘與計時器不工作

這不行,爲什麼?有什麼更好的辦法可以做到這一點?嘗試搜索,沒有發現任何工作對我來說...斷點從來沒有打OnStop方法...

static void Main() 
    { 
     WriteLine("service has started"); 
     timer = new Timer(); 
     timer.Enabled = true; 
     timer.Interval = 1000; 
     timer.AutoReset = true; 
     timer.Start(); 
     timer.Elapsed += scheduleTimer_Elapsed; 
    } 

    private static void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     WriteLine("service is runs again"); 
    } 

    public static void WriteLine(string line) 
    { 
     Console.WriteLine(line); 
    } 
+0

在運行服務之前啓動計時器? – DavidG 2014-11-14 13:27:59

+1

不確定,但是在'timer.Elapsed + = ..'語句之後添加'timer.Enabled = True'而不是'timer.Start()'之前呢? – 2014-11-14 13:28:30

+1

閱讀線程定時器http://msdn.microsoft.com/en-us/library/swx5easy.aspx – 2014-11-14 13:29:55

回答

2

我以前有點相同的情況。我使用下面的代碼,它爲我工作。

// The main Program that invokes the service 
static class Program 
{ 

    /// <summary> 
    /// The main entry point for the application. 
    /// </summary> 
    static void Main() 
    { 
     ServiceBase[] ServicesToRun; 
     ServicesToRun = new ServiceBase[] 
     { 
      new Service1() 
     }; 
     ServiceBase.Run(ServicesToRun); 
    } 
} 


//Now the actual service 

public partial class Service1 : ServiceBase 
{ 
    public Service1() 
    { 
     InitializeComponent(); 
    } 

    protected override void OnStart(string[] args) 
    { 
     ///Some stuff 

     RunProgram(); 

     ///////////// Timer initialization 
     var scheduleTimer = new System.Timers.Timer(); 
     scheduleTimer.Enabled = true; 
     scheduleTimer.Interval = 1000; 
     scheduleTimer.AutoReset = true; 
     scheduleTimer.Start(); 
     scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed); 
    } 

    protected override void OnStop() 
    { 
    } 

    void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e) 
    { 
     RunProgram(); 
    } 

    //This is where your actual code that has to be executed multiple times is placed 
    void RunProgram() 
    { 
    //Do some stuff 
    } 
} 
+0

所以你不要調用Main方法?你只需再次調用RunProgram?但是,您是否需要調用Main,因爲有Timer集? – MrProgram 2014-11-14 13:50:08

+0

當服務第一次運行時,主要的方法被調用。然後我們需要重新運行RunProgram – 2014-11-14 13:51:15

+0

嗯..有了這段代碼,我的scheduleTimer_Elapsed根本就不會被調用 – MrProgram 2014-11-14 13:55:54

相關問題