简体   繁体   English

Asp.Net - 使用 IHostedService 的计划任务

[英]Asp.Net - Scheduled Task using IHostedService

I'm working on an ASP.NET web application written in C# and hosted in an Azure virtual machine using IIS 10 as a web server.我正在开发一个用 C# 编写并托管在 Azure 虚拟机中的 ASP.NET Web 应用程序,使用 IIS 10 作为 Web 服务器。 I have to schedule a background task to run once a day.我必须安排一个后台任务每天运行一次。 To achieve this I created the following DailyTask class:为此,我创建了以下DailyTask类:

public class DailyTask : IHostedService {

    public Task StartAsync(CancellationToken cancellationToken) {
        Debug.WriteLine("start");
        Task.Run(TaskRoutine, cancellationToken);
        return Task.CompletedTask;
    }

    public Task StopAsync(CancellationToken cancellationToken) {
        Debug.WriteLine("stop");
        return null;
    }

    public Task TaskRoutine() {
        while (true) {
            try {
                /* ... */

                DateTime nextStop = DateTime.Now.AddDays(1);
                var timeToWait = nextStop - DateTime.Now;
                var millisToWait = timeToWait.TotalMilliseconds;
                Thread.Sleep((int)millisToWait);
            }

            catch (Exception e) {
                Debug.WriteLine(e);
            }
        }
    }
}

To start this task I added the following statement in my Startup class:为了开始这个任务,我在Startup类中添加了以下语句:

public class Startup {
    public void ConfigureServices(IServiceCollection services) {
        /* ... */
        services.AddSingleton<Microsoft.Extensions.Hosting.IHostedService, HiddenUserCleaner>();
        /* ... */
    }
}

After a deploy on my test server, I observed that this solution works fine.在我的测试服务器上部署后,我观察到此解决方案工作正常。 But is it reliable?但它可靠吗? Can there be problems if used in production?如果在生产中使用会不会有问题?

It's not safe.这不安全。 Take a look at the guide here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio看看这里的指南: https : //docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio

If the app shuts down unexpectedly (for example, the app's process fails), StopAsync might not be called.如果应用程序意外关闭(例如,应用程序的进程失败),则可能不会调用 StopAsync。 Therefore, any methods called or operations conducted in StopAsync might not occur.因此,在 StopAsync 中调用的任何方法或执行的操作可能不会发生。

It's not the case exactly, but it assumes that the application can be restarted.情况并非完全如此,但它假定应用程序可以重新启动。 Same thing goes with application pool which restarts occasionally.偶尔重新启动的应用程序池也是如此。

Overall, this will not assure that it will run daily.总的来说,这并不能保证它会每天运行。 If the application restarts frequently for whatever reason, it could be that it never runs.如果应用程序由于某种原因频繁重启,则可能是它从未运行过。

The same is true with libraries like hangfire.像hangfire这样的库也是如此。

Other solutions could be web jobs, or you could check if it has executed today by using some kind of persistence like a database that stores the last execution time and the IHostingService will check every some time and on startup whether or not it should execute the background job and act accordingly.其他解决方案可能是 Web 作业,或者您可以通过使用某种持久性(例如存储上次执行时间的数据库)来检查它今天是否已执行,并且IHostingService将每隔一段时间和启动时检查它是否应该执行后台工作并采取相应的行动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM