Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

c# - How to run a background service on demand - not on application startup or on a timer

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>();

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.

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"):

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-5.0&tabs=visual-studio

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?

Thanks

question from:https://stackoverflow.com/questions/65938752/how-to-run-a-background-service-on-demand-not-on-application-startup-or-on-a-t

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

The work flow goes like this:

  1. Caller sends a request to the service with some parameters
  2. Service generates a "job" object and returns an ID immediately via 202 (accepted) response
  3. Service places this job in to a queue that is being maintained by a BackgroundService
  4. 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
  5. Service finishes the job, puts the job in to a "completed" state and goes back to waiting on the queue to produce more jobs

Here is a very long-winded explanation on how it works: https://stackoverflow.com/a/63429262/1204153

Here is an example I made a while back: https://github.com/sonicmouse/ComputationService


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...