如何按需运行后台服务 - 而不是在应用程序启动或计时器上 [英] How to run a background service on demand - not on application startup or on a timer
问题描述
在 .Net 5 Web API 中,我想运行一个发送批量电子邮件和 SMS 的后台任务.我知道我可以创建一个从 BackgroundService 继承的服务,然后像这样在 Startup.ConfigureServices 方法中将它添加到 DI 容器中:
In a .Net 5 Web API, I would like to run a background task that sends out bulk emails and SMSes. I know I can create a service that inherits from BackgroundService, and then add it to the DI Container in the Startup.ConfigureServices method like this:
services.AddHostedService<EmailAndSmsService>();
但这会立即运行服务 - 即在应用程序启动时.我想在 API 收到来自前端的请求时运行该服务.即在控制器的操作方法中.
But that runs the service immediately - i.e. on application startup. I would like to run the service when the API receives a request from the front-end. i.e. in a controller's action method.
我一直在研究带有托管服务的后台任务";在 Microsoft 的文档中,如果我没记错的话,这就是我需要做的(查看标题为在后台任务中使用范围服务"的部分):
I've been looking at "Background tasks with hosted services" on Microsoft's documentation, and if I'm not mistaken, this is what i need to do (Look at the section titled "Consuming a scoped service in a background task"):
这是正确的吗?我是否基本上需要创建两个服务,一个执行实际工作,另一个调用执行实际工作的服务?我走在正确的道路上吗?
Is this correct? Do I basically need to create two services, one that does the actual work, and one that calls the service that does the actual work? Am I on the right path?
谢谢
推荐答案
需要看一个排队后台服务";您可以提交工作"的地方它将在后台队列中执行这些作业.
You need to look at a "queued background service" where you can submit "jobs" to it and it will perform those jobs in a background queue.
工作流程如下:
- 调用者向服务发送带有一些参数的请求
- 服务生成一个作业"对象并通过 202(接受)响应立即返回一个 ID
- Service 将此作业放入由
BackgroundService
维护的队列中 - 调用者可以使用此作业 ID 查询作业状态并获取有关已完成多少以及剩余多少的信息
- 服务完成工作,将工作置于已完成"状态状态并返回等待队列以产生更多作业
这是关于它如何工作的一个非常冗长的解释:https://stackoverflow.com/a/63429262/1204153
Here is a very long-winded explanation on how it works: https://stackoverflow.com/a/63429262/1204153
这是我之前做的一个例子:https://github.com/sonicmouse/ComputationService
Here is an example I made a while back: https://github.com/sonicmouse/ComputationService
这篇关于如何按需运行后台服务 - 而不是在应用程序启动或计时器上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!