.NET Core BackgroundService仅运行一次 [英] .NET Core BackgroundService Run Only Once

查看:171
本文介绍了.NET Core BackgroundService仅运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建.net核心BackgroundService控制台应用程序.默认模板提供了一个具有ExecuteAsync()方法的Worker类,这很好.

I am creating a .net core BackgroundService console application. The default template provides a Worker class that has ExecuteAsync() method, which is great.

我的计划是使用Windows Task Scheduler安排每天执行一次控制台应用程序.但是,我意识到ExecuteAsync()是一个连续执行的方法.所以我的问题是-如何只执行一次ExecuteAsync()中的代码,然后终止工作器?我可能还有其他进程正在运行,因此每个进程都需要运行一次并自行终止.

My plan is to use a Windows Task Scheduler to schedule to execute the console app once a day. However, I realized the ExecuteAsync() is a continuously executing method. So my question is -- how do I execute the codes in ExecuteAsync() only once and then terminate the Worker? I might have other processes still running, so each individual process needs to run once and terminate itself.

还是BackgroundService对我来说不是最佳选择?

Or is BackgroundService not the best choice for me?

推荐答案

FlashOver的答案是正确的- ExecuteAsync 被调用一次.不会重复.

The answer from FlashOver is correct -- ExecuteAsync is called once. Not repeatedly.

如果您希望在特定时间在 IHostedService 中发生某些事情,请阅读

If you want to have something happen at a specific time in a IHostedService, read this article from Microsoft.

如果链接消失了,我将在此处粘贴代码:

I will paste the code here in case the link rots away:

public class TimedHostedService : IHostedService, IDisposable
{
    private int executionCount = 0;
    private readonly ILogger<TimedHostedService> _logger;
    private Timer _timer;

    public TimedHostedService(ILogger<TimedHostedService> logger)
    {
        _logger = logger;
    }

    public Task StartAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Timed Hosted Service running.");

        _timer = new Timer(DoWork, null, TimeSpan.Zero, 
            TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        var count = Interlocked.Increment(ref executionCount);

        _logger.LogInformation(
            "Timed Hosted Service is working. Count: {Count}", count);
    }

    public Task StopAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Timed Hosted Service is stopping.");

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}

以这种方式注入

services.AddHostedService<TimedHostedService>();

现在,请记住,如果您的应用程序在一个以上的实例中水平扩展,那么您将运行多个计时器.这通常不是一件好事.

Now, keep in mind that if your application scales horizontally where you have more than one instance then you will have more than one timer running. This generally is not a good thing.

在需要任务在一天的特定时间运行的情况下,我会使用Azure功能设置为CRON作业.

In cases where I need a task to run at a specific time of day I use an Azure Function set up as a CRON job.

这篇关于.NET Core BackgroundService仅运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆