How can I use a service outside of Startup.cs in my ASP.NET Core Application?

asp.net asp.net-core c# entity-framework entity-framework-core

Question

I has an ASP.NET Core application that serves as a sort of "job scheduler", thus I need to have the application run a cron job for configured jobs. I figured out a method to do this, but unfortunately, it only works in the Startup.cs file using the IServiceCollection abstract class. Due to the nature of this application, I need to be able to add a cron job in my controller when a post request is made.

Here is how I am adding a cron job inside Startup.cs:

public void ConfigureServices(IServiceCollection services)
        {
                // Basic config code above here

                services.AddCronJob<CronJob>(c =>
                {
                    c.TimeZoneInfo = TimeZoneInfo.Local;
                    c.CronExpression = @"" + cronEx;
                    Console.WriteLine(c.CronExpression);
                });
            }
        }

Here is my API controller and what I am trying to do:

// POST: api/Jobs
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://aka.ms/RazorPagesCRUD.
[HttpPost]
public async Task<ActionResult<Job>> PostJob(Job job)
{
    _context.Job.Add(job);
    await _context.SaveChangesAsync();

    services.AddCronJob<CronJob>(c =>
    {
          c.TimeZoneInfo = TimeZoneInfo.Local;
          c.CronExpression = @"" + job.CronExpression;
    });

    return CreatedAtAction("GetJob", new { id = job.Id }, job);
}

I'm not totally sure if this is possible, but any insight would be helpful.

1
0
3/5/2020 1:27:03 AM

Popular Answer

First question if you need to add this cron job as new service every time.

If you want to use app as scheduler then the best idea is to use IHostedService - Documentation link.

Here you have some example of how to use IHostedService to make simple scheduler - Scheduler example based on IHostedService

0
3/5/2020 1:35:20 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow