2014-11-14 43 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

相关问题