我怎样才能弄清楚为什么Windows服务中的计时器事件没有触发?

时间:2017-01-07 01:47:32

标签: c# .net windows service windows-services

我有一项非常基本的服务

using System.ServiceProcess;
using System.Timers;
using SystemTimer = System.Timers.Timer;
using System.Net;
using System.Data.SqlClient;
using System;

namespace ServiceThatConnectsToADb
{
    public class LrcArchiver : ServiceBase
    {
        private static SystemTimer PageLoadTimer = new SystemTimer(5000);

        public LrcArchiver()
        {
            ServiceName = "SO Archiver";
            CanStop = true;
            CanPauseAndContinue = true;
            AutoLog = true;
            PageLoadTimer.Elapsed += new ElapsedEventHandler(WritePageToDb);
        }

        protected override void OnStart(string[] args)
        {
            EventLog.WriteEntry(ServiceName + " started");
        }

        protected override void OnStop()
        {
            EventLog.WriteEntry(ServiceName + " stopped");
            PageLoadTimer.Enabled = false;
        }

        protected void WritePageToDb(object source, ElapsedEventArgs e)
        {
            try
            {
                string html;
                using(WebClient client = new WebClient())
                {
                    html = client.DownloadString("http://stackoverflow.com");
                }
                EventLog.WriteEntry("html = " + html.Substring(0, 100));
                using(SqlConnection connection = new SqlConnection("Data Source=DESKTOP-300NQR3\\SQLEXPRESS;Initial Catalog=SoArchive;Integrated Security=True"))
                {
                    string nonQuery = $"INSERT INTO [dbo].[Homepage] ([Html]) VALUES ('{html}')";
                    using(SqlCommand command = new SqlCommand(nonQuery, connection))
                    {
                        bool succeeded = command.ExecuteNonQuery() == 1;
                        EventLog.WriteEntry(succeeded ? "Saved!" : "Not Saved");
                    }
                }
            }
            catch(Exception ex)
            {
                EventLog.WriteEntry("uh-oh! " + ex.Message);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            ServiceBase.Run(new LrcArchiver());
        }
    }
}

我已经安装并启动了,但WritePageToDb方法似乎没有触发,因为它的WriteEntry都没有显示。我明白了

  

SO Archiver开始

但之后什么都没有。

知道为什么会这样或者我如何调试才能找到原因?

2 个答案:

答案 0 :(得分:3)

您只是将其设置为有效,但您没有启动计时器。

protected override void OnStart(string[] args)
{
    PageLoadTimer.Enabled = true;
    EventLog.WriteEntry(ServiceName + " started");
}

答案 1 :(得分:-1)

试试这个,我在某个时间点遇到问题,这对我有用。在此部分示例中,计时器设置为1分钟

  TimerCallback callbacktimer;
  Timer IntervalCheck;


  protected override void OnStart(string[] args) {

   try {

    callbacktimer = new TimerCallback(SomeMethode);
    IntervalCheck = new Timer(callbacktimer, null, TimeSpan.Zero, new TimeSpan(0, 1, 0));



    base.OnStart(args);
   } catch (Exception ex) {

   }

  }

  private void SomeMethode(object o) {


  }