This is my Job which needs to be executed every one minute, this has the dependency on logger
public class RefreshJob :IJob
{
public RefreshJob(IContainerFactory containerFactory)
{
_logger = containerFactory.GetInstance<ILogger>();
}
public Task Execute(IJobExecutionContext context)
{
return Task.Run(() =>
{
_logger.Information("Executing sample job");
_logger.Information($"Name: {context.JobDetail.Key.Name}");
_logger.Information($"Description: '{context.JobDetail.Description}'");
_logger.Information($"Fire time utc: {context.FireTimeUtc:yyyy-MM-dd HH:mm:ss zzz}");
});
}
}
Here is my dependency injection
var containerFactory = new ContainerFactory();//class with GetInstance method.
_builder.Register(c => new RefreshJob(containerFactory)).SingleInstance();
This is how I get the scheduler reference
static async Task<IScheduler> GetScheduler()
{
var factory = new StdSchedulerFactory();
return await factory.GetScheduler();
}
and I use it in start method of my windows service
public void Start()
{
Task<IScheduler> scheduler = GetScheduler();
scheduler.Wait();
_jobScheduler = scheduler.Result;
_jobScheduler.Start();
//Trigger
IJobDetail job = JobBuilder.Create<RefreshCacheJob>().Build();
ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("RefreshJob", "GroupName")
.StartAt(DateTime.Now)
.WithPriority(1)
.Build();
_jobScheduler.ScheduleJob(job, trigger);
}
But nothing happens. By the way, I am using Quartz scheduler inside windows service
Updated the error
Quartz.SchedulerException: Problem instantiating class 'Scheduler.RefreshJob' ---> System.ArgumentException: Cannot instantiate type which has no empty constructor Parameter name: RefreshJob
If there's a need to inject a service into the job, follow this guide as @foips commented. Basically you need the following line in your DI container:
services.AddQuartz(q =>
{
...
q.UseMicrosoftDependencyInjectionJobFactory();
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With