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

本文关键字:服务 一次 计时器 工作 分钟 重新运行 | 更新日期: 2023-09-27 18:30:20

我有一个服务,我想每 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);
    }

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

我之前的情况有点相同。我使用了以下代码,它对我有用。

// 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
    }
}