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 设置为 以管理员身份运行 【属性-安全】