1

我有以下代码,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 类中评论开始“ServiceBase [] ...”的部分并取消注释“Processing ...”时,它工作正常。

但是当我的代码作为 Windows 服务运行时 - 什么也没有发生

4

2 回答 2

0

正如我所见,您的服务不会一直运行 this.timer.Interval = ScanPeriod.period * 60000;。对于您的方案,而不是使用带有计时器的 Windows 服务(并花时间解决问题),我建议使用计划任务(如this answer建议的那样)。它引用了 Jon Gallow 的一篇文章,其中给出了许多使用计划任务更好的理由。

如果您正在编写运行计时器的 Windows 服务,您应该重新评估您的解决方案。

于 2015-10-27T08:14:31.273 回答
0

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

  static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[] 
        { 
            new SyncProcess() 
        };
        ServiceBase.Run(ServicesToRun);    
        Console.ReadLine();
    }
于 2015-10-27T07:17:08.463 回答