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();
        }
    }
}

 

转载于:https://www.cnblogs.com/bwangff/p/4233518.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值