Dotnet Core Windows Service

來源:互聯網
上載者:User

標籤: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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.