C#设置Windows服务无限次运行

时间:2018-03-22 07:53:20

标签: c#

我在服务器中有一个Windows服务,它插入到数据库中。我希望它每小时运行一次,无限次(直到我停止它)。它运行几次,然后停止。 到目前为止,我没有看到任何模式。如果我将它设置为每5秒运行多次,如果我将其设置为每1小时它只运行几次,等等。 我不希望使用任务调度程序的解决方案,而是相应地修改代码或告诉我错误的位置。

我不知道代码或服务器是否有问题。我应该改变什么?  我有2个cs文件:

目前在100秒进行测试。 注释掉不起作用的部分: Service1.cs

  static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    /// 


    static System.Timers.Timer timer;

    //static void Main(string[] args)
    //{
    //    var periodTimeSpan = TimeSpan.FromSeconds(5);
    //    timer = new System.Timers.Timer(periodTimeSpan.TotalSeconds);
    //    timer.Elapsed += Timer_Elapsed;
    //    timer.Start();
    //}

    private static void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        //Do some stuff

        timer.Start();
    }

    static void Main()
    {
        Service1 myService = new Service1();
        myService.OnDebug();
        System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);

        //// 0, ,0, 10 seconds. adjust accordingly.
        //TimeSpan interval = new TimeSpan(0, 0, 5);

        //for (int i = 0; i < 5; i++)
        //{

        //    Thread.Sleep(interval);
        //}

        var periodTimeSpan = TimeSpan.FromSeconds(100);
        timer = new System.Timers.Timer(periodTimeSpan.TotalSeconds);
        timer.Elapsed += Timer_Elapsed;
        timer.Start();

        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new Service1()
        }
        ;
        ServiceBase.Run(ServicesToRun);



    }

Program.cs(插入数据库)

    var startTimeSpan = TimeSpan.Zero;
        var periodTimeSpan = TimeSpan.FromSeconds(100);
        var timer = new System.Threading.Timer((e) =>
         {

//insert data to database//

        } ,null, startTimeSpan, periodTimeSpan);

0 个答案:

没有答案