NetCore windowsService 看門狗應用程序

  public class DogService : BackgroundService
    {

        public override Task StartAsync(CancellationToken cancellationToken)
        {
            return base.StartAsync(cancellationToken);
        }
        /// <summary>
        ///  每一秒執行一次
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                  StartService();
                  await Task.Delay(1000 * 60 , stoppingToken);
            }
        }

        public override Task StopAsync(CancellationToken cancellationToken)
        { 
            return base.StopAsync(cancellationToken);
        }  

        private void StartService()
        {
            List<string> services = new List<string>() { "ChargRabbitService" };
            foreach (var item in services)
            {
                ServiceController service = new ServiceController(item);
                try
                {
                    if (service.Status != ServiceControllerStatus.Running)
                    {

                        service.Start();
                        service.WaitForStatus(ServiceControllerStatus.Running);

                    }
                }
                catch (Exception ex)
                {
                    continue;
                }
            }  
        }
    }

main

    static class Program
    {
        static  void Main(string[] args)
        {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.AddJsonFile("appsettings.json", true, true);
            var ConfigRoot = builder.Build();//根節點
            IServiceCollection Services = new ServiceCollection();
            
            Services.AddLogging(log => { log.AddConsole(); log.AddNLog(); log.SetMinimumLevel(LogLevel.Error); });  
            //  
            using (ServiceProvider provider = Services.BuildServiceProvider())
            {
                

            }
            CreateHostBuilder(args).Run();
        }

        public static IHost CreateHostBuilder(string[] args)
        {
            var builder = Host.CreateDefaultBuilder(args)
                 .ConfigureServices((hostContext, services) =>
                 {
                     services.AddHostedService<DogService>();
                 }).UseWindowsService();
            var host = builder.Build();

            return host;
        }
    }

將發佈的exe 設置爲 以管理員身份運行 【屬性-安全】

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章