Equivalent of Ihostedservice in asp.net framework for background tasks

前端 未结 2 818
忘了有多久
忘了有多久 2021-02-04 03:59

I have a restful micro service (web api) in .net 4.6.2 and I want to call a fire and forget function each time after certain endpoints are called to do some database cleanup wor

2条回答
  •  死守一世寂寞
    2021-02-04 04:14

    I guess it's a bit too late, but for someone with the same issue..

    Do you know Quartz.NET and Hangfire.io ?

    Maybe one of those both could be a very useful tool in your situation. I used it in many applications, and never had any issue.

    For example, in Quartz.Net, you first have to create a "job" (it's the term used for this kind of background services) by creating a class implementing IJob interface:

    public class HelloJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            await Console.Out.WriteLineAsync("Greetings from HelloJob!");
        }
    }
    

    Then, you have to define when you want to check that job, there are many ways (CRON for example) but we just gonna use a simple schedule here :

            StdSchedulerFactory factory = new StdSchedulerFactory();
            IScheduler scheduler = await factory.GetScheduler();
    
            await scheduler.Start();
    
            // define the job
            IJobDetail job = JobBuilder.Create()
                .WithIdentity("job1", "group1")
                .Build();
    
            // Trigger the job to run now, and then repeat every 20 seconds
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")
                .StartNow()
                .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(20)
                    .RepeatForever())
                .Build();
    
            // Tell quartz to schedule the job using our trigger, DON'T FORGET THIS ONE
            await scheduler.ScheduleJob(job, trigger);
    

    You are in a micro services architecture based on windows service. You should be able to catch all "graceful" shutdown of your application. In these cases, you have to shutdown properly the Quartz scheduler :

    await scheduler.Shutdown();
    

    I personally really like these kinds of approach. It's reusable (you just have to schedule a new job here) and easy to get into that for any developer on your team.

    I hope it will help you a bit with your issue.

提交回复
热议问题