定时器不工作,每x分钟重新运行一次

时间:2014-11-14 13:24:29

标签: c# windows-services

我有一项服务,我希望每隔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);
    }

1 个答案:

答案 0 :(得分: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
    }
}