简体   繁体   中英

Windows service only executes once

I've written my first .Net Service using TopShelf and I'm experiencing an issue where the service code only executes a single time.

I have configured the service main as follows

    private static void Main(string[] args)
    {
        HostFactory.Run(x =>
        {
            x.Service<ServiceProcess>(s =>
            {
                s.ConstructUsing(name => new ServiceProcess());
                s.WhenStarted(tc => tc.Start());
                s.WhenStopped(tc => tc.Stop());
            });

            x.StartAutomatically();
            x.RunAs(Username, Password);
        });
    }

And the method that runs only a single time is as follows.

using System.Timers;

public class ServiceProcess
{
    private readonly Timer _timer;

    public ServiceProcess()
    {
        _timer = new Timer(1000) { AutoReset = false };
        _timer.Elapsed += (sender, eventArgs) => EventLog.WriteEntry(ServiceName, "It is " + DateTime.Now, EventLogEntryType.Information);
    }
}

I can see in the event log that the message is written correctly but it only occurs a single time. Since this is the most basic of configuration I'm not certain why this isn't working. I have played with the timing and attempted to add exception handling but ultimately it appears to simply not be running again.

Note that my Start() and Stop() methods are doing a _timer.Start() and _timer.Stop() respectively.

将计时器的AutoReset属性设置为true。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM