c# Windows 带有定时器的服务不执行代码

c# Windows service with Timer not executing code

我有以下代码,windows服务启动时没有执行

我在这里找到了解决方案,但它们对我不起作用。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Configuration;
using System.Threading.Tasks;

namespace TFS_JIRA_sync
{
    public partial class SyncProcess : ServiceBase
    {

        public SyncProcess()
        {
            InitializeComponent();
        }

        private System.Timers.Timer timer = new System.Timers.Timer();

        protected override void OnStart(string[] args)
        {

            this.timer.Interval = ScanPeriod.period * 60000; //turn minutes to miliseconds            
            this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);//OnTimer;            
            this.timer.Enabled = true;
            this.timer.AutoReset = true;
            this.timer.Start();
        }

        private void OnTimer(object sender, System.Timers.ElapsedEventArgs e)
        {
            Processing proc = new Processing();
            proc.doProcess();
        }

        protected override void OnStop()
        {
        }
    }
}

在程序中:

using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Threading.Tasks;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]


namespace TFS_JIRA_sync
{
    static class Program
    {
        /// <summary>
        /// Главная точка входа для приложения.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] 
            { 
                new SyncProcess() 
            };
            ServiceBase.Run(ServicesToRun);

            //Processing proc = new Processing();
            //proc.doProcess();

        }
    }
}

当我在 Programm class 中注释开始 "ServiceBase[]..." 的部分并取消注释 "Processing ..." 时,它工作正常。

但是当我的代码 运行 作为 Windows 服务时 - 没有任何反应

将 Console.ReadLine() 放入您的代码中:

  static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new SyncProcess() 
        };
        ServiceBase.Run(ServicesToRun);    
        Console.ReadLine();
    }

据我所知,您的服务不会一直 运行 this.timer.Interval = ScanPeriod.period * 60000;。对于您的场景 我建议使用计划任务(如 answer 所建议的),而不是使用带有计时器的 windows 服务(并花时间解决问题)。 它引用了 Jon Gallow 的 article,它给出了为什么使用计划任务更好的很多原因。

If you're writing a Windows Service that runs a timer, you should re-evaluate your solution.