码迷,mamicode.com
首页 > Windows程序 > 详细

Dotnet Core Windows Service

时间:2018-01-08 16:47:44      阅读:539      评论:0      收藏:0      [点我收藏+]

标签:iba   start   代码   reset   gets   onstop   nts   runner   win   

在dotnet 中有topshelf 可以很方便的写windows 服务并且安装也是很方便的,命令行 运行.exe install 就直接把exe 程序安装成windows 服务。当然

代码也要做相应的修改,具体的可以参照例子。

在dotnet core 2.0 中 我们也有一个很方便的dll 来试用 

https://github.com/PeterKottas/DotNetCore.WindowsService

通过Nuget来安装 Using nuget: Install-Package PeterKottas.DotNetCore.WindowsService

方便多个服务我们先定义一个接口

public interface IBaseService
{
void Start();
void Stop();
}

具体的实现呢 我举个例子,在例子中我们试用了个Timer,定时的完成某些任务,这样 我们就可以同时写好几个service 只要继续 IBaseService 就行,也比较方面安装

public class SyncService : IBaseService
{
private readonly System.Timers.Timer _timer;
private readonly ILogger logger;
public SyncService( ILoggerFactory loggerFactory)
{

_timer = new System.Timers.Timer(10000);
_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

_timer.Interval = 2000;

_timer.AutoReset = true;
_timer.Enabled = false;
logger = loggerFactory.CreateLogger<SyncService>();
}


private void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine(string.Format("SyncService:{0:yyyy-MM-dd HH:mm:sss}", DateTime.Now));
_timer.Enabled = false;

try
{
//do some job;
}
catch (Exception ex)
{
logger.LogError("SyncService Error {0}:", ex.Message);
}
Console.WriteLine(string.Format("SyncService:{0:yyyy-MM-dd HH:mm:sss}", DateTime.Now));

Thread.Sleep(5 * 60 * 1000);

_timer.Enabled = true;

}
private async Task<HttpResponseMessage> SyncData()
{
string url = configModel.DatabaseIncrementUrl;
var httpClient = new HttpClient();
return await httpClient.GetAsync(url);
}


public void Start()
{
_timer.Start();
_timer.Enabled = true;
}
public void Stop()
{
_timer.Stop();
_timer.Enabled = false;
}
}

 

class Program
{
static void Main(string[] args)
{

IConfigurationRoot Configuration;
// ILoggerFactory LoggerFactory;

var builder = new ConfigurationBuilder()
.SetBasePath(Path.Combine(AppContext.BaseDirectory))
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();

Configuration = builder.Build();

var services = new ServiceCollection();

services.AddOptions();
services.Configure<ConfigModel>(Configuration.GetSection("ConfigSetting"));
services.AddSingleton<IConfiguration>(Configuration);

services.AddTransient<ILoggerFactory, LoggerFactory>();

services.AddTransient<IBaseService, SyncService>();
services.AddTransient<IBaseService, CreateDBService>();
services.AddTransient<IBaseService, OnLineOrderService>();

var serviceProvider = services.BuildServiceProvider();

ServiceRunner<ServiceFactory>.Run(config =>
{
var name = config.GetDefaultName();
config.Service(serviceConfig =>
{
serviceConfig.ServiceFactory((extraArguments, controller) =>
{
return new ServiceFactory(serviceProvider.GetService<IEnumerable<IBaseService>>(), controller);
});
serviceConfig.OnStart((service, extraArguments) =>
{
Console.WriteLine("Service {0} started", name);
service.Start();
});

serviceConfig.OnStop(service =>
{
Console.WriteLine("Service {0} stopped", name);
service.Stop();
});

serviceConfig.OnError(e =>
{
Console.WriteLine("Service {0} errored with exception : {1}", name, e.Message);
});
});

config.SetName("SAASService");
config.SetDescription("SAAS Service For All Saas Client");
config.SetDisplayName("SAAS Service");
});
}
}

Dotnet Core Windows Service

标签:iba   start   代码   reset   gets   onstop   nts   runner   win   

原文地址:https://www.cnblogs.com/jfliuyun/p/8242945.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!