你好。
我有一个基于Net Core 3.1的Web API,其中包含一个服务,每隔X分钟就要运行一次数据迁移(我只是在测试它),但是我有两个问题。
- 为了让服务运行,我必须先运行我的API的某些URL。问题是:如何使这个服务自动启动,而不需要运行任何API?
- 当我停止使用API几分钟后,服务就停止工作了。问题是:如何让服务“永久”保持运行状态?
我必须强调,我的Web API托管在Web托管中,我无法访问所有IIS功能。
这是我的代码,提前感谢你的帮助。
MySuperService.cs
public class MySuperService : IHostedService, IDisposable
{
private bool _stopping;
private Task _backgroundTask;
private static readonly log4net.ILog log =log4net.LogManager.GetLogger(typeof(MySuperService));
public Task StartAsync(CancellationToken cancellationToken)
{
Console.WriteLine("MySuperService is starting.");
log.Info("MySuperService is starting.");
_backgroundTask = BackgroundTask();
return Task.CompletedTask;
}
private async Task BackgroundTask()
{
int contador = 1;
while (!_stopping)
{
Console.WriteLine("MySuperService is working--> " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
log.Info("MySuperService is working--> " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
await Task.Delay(TimeSpan.FromMinutes(3));
contador++;
}
Console.WriteLine("MySuperService background task is stopping.");
log.Info("MySuperService background task is stopping.");
}
public async Task StopAsync(CancellationToken cancellationToken)
{
Console.WriteLine("MySuperService is stopping.");
log.Info("MySuperService is stopping.");
_stopping = true;
if (_backgroundTask != null)
{
// TODO: cancellation
await BackgroundTask();
//await _backgroundTask;
}
}
public void Dispose()
{
Console.WriteLine("MySuperService is disposing.");
log.Info("MySuperService is disposing.");
}
}
Program.cs
public class Program
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Program));
public static void Main(string[] args)
{
...
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).ConfigureServices((hostContext, services) =>
{
services.AddHostedService<MySuperService>();
});
}