Bike_dotnet
Bike_dotnet

Reputation: 254

Best way to CRON a service function

We have a .net 6 worker service.

Within this worker there is an injected scoped dbcontext as well as an injected service that uses this context.

The service looks something like this:

Publc ServiceConstructor(Mycontext context)
{
    _dbContext = context;  <---- scoped injected db
}

Public async Task DoWork()
{
    //Do Work
}

Startup has:

services.AddScoped<Mycontext>();
services.AddScoped<Myservice>()

And in my worker's ExcecuteAsync()

using(var scope = _serviceProvider.CreateScope()){

   //get service here using getrequiredservice
}

The problem I am facing is that I need to schedule doWork using cron. But also keeping in mind that a second and 3rd service will be added and 2 of them will run at the same time and the 3rd on a different time. But all 3 should be easy to set a new time.

Is there an easy way to schedule all 3 service functions individually?

All 3 will use the same database.

Upvotes: 1

Views: 602

Answers (1)

Stefan
Stefan

Reputation: 17668

It depends a bit on your model; but in general: the DbContext should be short lived.

Meaning: You will not be dealing with the same instance of the DbContext for the lifetime of the service, but instead: you must request a new one, preferably from the framework at function execution.

This is similar as how it works when dealing with HTTP requests. Per request you'll have your "own" DbContext. An interresting question on how connection pooling and such works in that scenario can be found here, and an general article on how to retrieve the DbContext can be found here.

So to sum it: if the service is long lived: don't inject it to the constructor as you did, but resolve it per CRON execution, which would be in the ExcecuteAsync through the scoped service provider.

I'll need more code to be more concrete. As for now, you seem to have all the building blocks and should be able to get to the solution. Let me know if you have further questions.

Upvotes: 1

Related Questions