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

查看:56
本文介绍了.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 任务计划程序来安排每天执行一次控制台应用程序.但是,我意识到 ExecuteAsync() 是一种持续执行的方法.所以我的问题是——如何只执行一次 ExecuteAsync() 中的代码然后终止 Worker?我可能还有其他进程仍在运行,因此每个进程都需要运行一次并自行终止.

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.

如果我需要在一天中的特定时间运行任务,我会使用设置为 CRON 作业的 Azure 函数.

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天全站免登陆