Custom Quartz.Net factory to use Autofac

The general project structure is as below, so that you will see we need to add

  • Autofac.dll
  • Quartz.dll

 

For quick adding them into your project, Visual Studio 2012 provides the NuGet package manager, 

MyJobContainer.cs

namespace HelloQuartzNet
{
    using System.Diagnostics;
    using Quartz;

    /// <summary>
    /// General purpose job container that runs any Action delegate.
    /// This expects the MergedJobDataMap to contain an Action named Action.
    /// </summary>
    public class MyJobContainer: IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                Console.WriteLine("Executing job:" + context.JobDetail.Description);

                var stopwatch = Stopwatch.StartNew();

                ((Action)context.MergedJobDataMap["Action"])();

                stopwatch.Stop();

                Console.WriteLine(string.Format("Done executing job ({0}): {1}", stopwatch.Elapsed, context.JobDetail.Description));
            }
            catch
            {
                Console.WriteLine(string.Format("Error executing job:" + context.JobDetail.Description));
            }
        }
    }
}

MyJobFactory.cs

namespace HelloQuartzNet
{
    using Autofac;
    using Quartz.Spi;

    /// <summary>
    /// Custom Quartz.NET job factory that uses Autofac container to resolve job types.
    /// </summary>
    public class MyJobFactory:IJobFactory
    {
        private readonly IComponentContext container;
        public MyJobFactory(IComponentContext container)
        {
            this.container = container;
        }

        public Quartz.IJob NewJob(TriggerFiredBundle bundle, Quartz.IScheduler scheduler)
        {
            return this.container.Resolve(bundle.JobDetail.JobType) as Quartz.IJob;
        }
    }
}

MyJobScheduler.cs

namespace HelloQuartzNet
{
    using Quartz;

    /// <summary>
    /// Wrapper the JobScheduler, and add trace message when operate
    /// </summary>
    public class MyJobScheduler
    {
        private readonly IScheduler scheduler;
        public MyJobScheduler(IScheduler scheduler)
        {
            this.scheduler = scheduler;
        }

        public void Start()
        {
            this.scheduler.Start();
        }

        public void Stop()
        {
            this.scheduler.Standby();
        }

        public void ScheduleJobs(string crons, string timeZone, string name, Action action)
        {
            foreach (string cron in crons.Split(';'))
            {
                this.ScheduleJob(cron, timeZone, name, action);
            }
        }

        public void ScheduleJob(string cronExpression, string timeZone, string description, Action action)
        {
            Console.WriteLine(string.Format(
                        "Scheduling job \"{0}\" with CRON expression \"{1}\"",
                        description,
                        cronExpression));

            var timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById(timeZone);

            var trigger = TriggerBuilder.Create()
                .StartNow()
                .WithCronSchedule(cronExpression, b => b.InTimeZone(timeZoneInfo))
                .Build();

            JobDataMap map = new JobDataMap();
            map.Add("Action", action);

            var job = JobBuilder
                .Create<MyJobContainer>()
                .UsingJobData(map)
                .WithDescription(description)
                .Build();

            this.scheduler.ScheduleJob(job, trigger);
        }
    }
}

Program.cs

You could also see how to use Cron in this link: http://www.cnblogs.com/sunjie9606/archive/2012/03/15/2397626.html

namespace HelloQuartzNet
{
    using Autofac;
    using Quartz.Impl;
    using Quartz.Spi;

    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();
            builder.RegisterType<MyJobFactory>().As<IJobFactory>();
            builder.RegisterType<MyJobScheduler>().AsSelf();
            builder.RegisterType<MyJobContainer>().AsSelf();
            builder.Register(c =>
            {
                var scheduler = new StdSchedulerFactory().GetScheduler();
                scheduler.JobFactory = c.Resolve<IJobFactory>();
                return scheduler;
            });

            var container = builder.Build();
            var myScheduler = container.Resolve<MyJobScheduler>();
            myScheduler.ScheduleJob("0/5 * * * * ? *", "UTC", "HelloQuartzNet Scheduler", () => Console.WriteLine("Testing Scheduler!"));
            myScheduler.Start();
        }
    }
}

 

posted @ 2015-01-19 13:02  bwangff  阅读(1381)  评论(0编辑  收藏  举报