如果使用IJobFactory,则DisallowConcurrentExecutionAttribute无法正常工作

时间:2018-11-08 14:33:55

标签: quartz-scheduler quartz.net

石英版本:2.3.2.0

预期的行为

DisallowConcurrentExecutionAttribute已添加到作业中,该作业应同步运行。

实际行为

该作业仍可以并发运行。

复制步骤

//main
public class MainClass
{
    private readonly IScheduler _scheduler;    

    public MainClass(IScheduler scheduler)
    {
        _scheduler = scheduler;
    }

    _scheduler.ScheduleJob(JobBuilder.Create<ICustomJob>().WithIdentity(JobKey.Create("uniqueKey")).Build(), TriggerBuilder.Create().WithSchedule(SimpleScheduleBuilder.RepeatSecondlyForever(5).StartNow().Build()));
    _scheduler.Start();
}

//NInject Composition Root
kernel.Bind<ICustomJob>().To<CustomJob>().InThreadScope();
kernel.Bind<IScheduler>.ToMethod(GetScheduler(kernel)).InSingletonScope();

private IScheduler GetScheduler(IKernel kernel)
{
    var scheduler = new StdSchedulerFactory().GetScheduler();
    scheduler.JobFactory = new NInjectJobFactory(kernel);
    return scheduler;
}

//NInjectJobFactory
public class NInjectJobFactory : IJobFactory
{
    private readonly IResolutionRoot _resolutionRoot;

    public NInjectJobFactory(IResolutionRoot resolutionRoot)
    {
        _resolutionRoot = resolutionRoot;
    }

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

    public void ReturnJob(IJob job)
    {
        _resolutionRoot.Release(job);
    }
}

//customJob
public interface ICustomJob : IJob
{

}

[DisallowConcurrentExecutionAttribute]
public class CustomJob : ICustomJob
{
    public void ExecuteJob(IJobExecutionContext context)
    {
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + DateTime.Now.ToString("T") + " CustomJob STARTED");
        Thread.Sleep(TimeSpan.FromSeconds(10));
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " " + DateTime.Now.ToString("T") + " CustomJob DONE");
    }
}

0 个答案:

没有答案