如何按需运行后台服务-不在应用程序启动或计时器上运行 [英] 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完成了多少工作以及还有多少要做的信息 服务完成工作,将工作置于完成"状态.状态,然后返回等待队列以产生更多工作
- Caller sends a request to the service with some parameters
- Service generates a "job" object and returns an ID immediately via 202 (accepted) response
- Service places this job in to a queue that is being maintained by a
BackgroundService
- Caller can query the job status and get information about how much has been done and how much is left to go using this job ID
- Service finishes the job, puts the job in to a "completed" state and goes back to waiting on the queue to produce more jobs
以下是有关其工作原理的非常冗长的解释: 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屋!