0

我用 Timers.Timer 做一个 Windows 服务。如果我作为控制台应用程序运行正常,但如果我将设置更改为 Windows 应用程序并评论所有控制台功能,则计时器不起作用。使用 Console.ReadLine(); 都好。但我不应该打开控制台。

 protected override void OnStart(string[] args)
    {
        AutoLog = false;
        SetTimer();
        Console.ReadLine();//if remove this line dont works
    }

设置定时器()

private void SetTimer()
    {
        mytimer = new Timer();
        mytimer.Interval = 2000;
        mytimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        mytimer.Enabled = true;
    }

OnTimedEvent()

 private void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        mytimer.Enabled = false;
        EventLog evento1 = new EventLog();
        evento1.Source = "scPublicar";
        evento1.Log = "Publicar";
        evento1.WriteEntry("Publicación corriendo,  OnTimedEvent");
        mytimer.Enabled = true;
    }

Program.cs Main()

 static void Main(string[] args)
    {
        ServiceBase[] servicesToRun;
        servicesToRun = new ServiceBase[] { new Publicar() };
        if (Environment.UserInteractive)
        {
            MethodInfo onStartMethod = typeof(ServiceBase).GetMethod("OnStart", BindingFlags.Instance | BindingFlags.NonPublic);
            foreach (ServiceBase service in servicesToRun)
            {
                onStartMethod.Invoke(service, new object[] { new string[] { } });
            }
        }
        else
            ServiceBase.Run(servicesToRun);
    }

谢谢你的回答

4

1 回答 1

2

当您在 Visual Studio 中运行/调试代码时Environment.UserInteractivetrue该过程会立即停止。这种行为是设计使然,您不应该做任何事情让它等待(例如 call Console.ReadLine())。

您需要将代码作为 Windows 服务(而不是控制台应用程序)运行,然后它将由服务控制管理器进行管理。这意味着您可以将其配置为在系统启动时自动启动并继续运行。您还可以通过 Windows 管理控制台 ( services.msc) 中的服务管理单元来启动和停止它。但要使其正常工作,您首先需要安装您的服务。

按着这些次序:

  1. 创建一个新的“Windows 服务”项目。您会注意到输出类型已设置为“Windows 应用程序”。
  2. 将代码粘贴到新Program.cs文件中并删除Console.ReadLine()语句
  3. 添加安装程序
  4. 安装服务
  5. 运行services.msc。您应该找到一个名为“Service1”的服务。右键单击它以启动它。
  6. 转到事件日志,您将每 2 秒找到一个条目

参考:

于 2018-03-08T09:17:34.627 回答