How to schedule task using Quartz.net 2.0?

▼魔方 西西 提交于 2019-12-04 09:53:22

To make Quartz.net work with an IoC container you need to have a factory class implementing IJobFactory:

public class AutofacJobFactory : IJobFactory
{
    private readonly IContainer _container;

    public AutofacJobFactory(IContainer container)
    {
        _container = container;
    }

    public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
    {
        return (IJob)_container.Resolve(bundle.JobDetail.JobType);
    }
}

The JobFactory instance then needs to be assigned to the scheduler in the initialization code:

ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
IScheduler scheduler = schedulerFactory.GetScheduler();
scheduler.JobFactory = new AutofacJobFactory(container);

And don't forget to register the job in the IoC container.

Have you tried scheduling the job after starting the scheduler?

public class ScheduleTaskConfig
{
    public static void StartScheduler()
    {
        ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

        IScheduler scheduler = schedulerFactory.GetScheduler();
        scheduler.Start(); //start here   

        //construct job info

        scheduler.ScheduleJob(emailSenderTask, emailSenderTrigger); //schedule here
    }
}
dcarson

You need to ensure that the AutofacJobFactory is responsible for instantiating the job. This means not using the JobBuilder object. Instead you should pass the details of the job to be created by the scheduler's AutofacJobFactory in the form of a JobDetailImpl object. Your working code would look something like the following.

ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

IScheduler scheduler = schedulerFactory.GetScheduler();
scheduler.JobFactory = new AutofacJobFactory(container);
scheduler.Start(); //start here  

// construct job info
JobDetailImpl jobDetail = new JobDetailImpl("emailSenderTask", null, typeof(QueuedEmailsSendTask));

TriggerKey emailSenderTriggerKey = new TriggerKey("emailSenderTrigger", "email");
ITrigger emailSenderTrigger = TriggerBuilder.Create()
    .WithIdentity(emailSenderTriggerKey)
    .WithSimpleSchedule(s => s.RepeatForever().WithIntervalInSeconds(5))
    .StartNow()
    .Build();

sched.ScheduleJob(jobDetail, trigger);

For a complete example, please see the following question How do I create a Quartz.NET’s job requiring injection with autofac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!