【问题标题】:windows service (with timer) not working without consoleWindows 服务(带计时器)在没有控制台的情况下无法工作
【发布时间】:2018-08-16 04:06:18
【问题描述】:

我用 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);
    }

谢谢你的回答

【问题讨论】:

    标签: c# .net console windows-services system.timers.timer


    【解决方案1】:

    当您在 Visual Studio 中运行/调试代码时,Environment.UserInteractivetrue,并且该过程立即停止。此行为是设计使然,您不应采取任何措施使其等待(例如,致电 Console.ReadLine())。

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

    按照以下步骤操作:

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

    参考资料:

    【讨论】:

    • 你是对的。如果我安装该服务,它工作正常。我正在寻找一种无需安装即可进行测试的方法,但这对我来说很好。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多