Welcome, guest! Login / Register - Why register?
Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)

Paste

Pasted as C# by RooDen ( 8 years ago )
using System;
using LightInject;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;

namespace QuartzTest
{
    class Program
    {
        static void Main(string[] args)
        {
            var container = new ServiceContainer();
            container.Register<IJobFactory>();
            container.Register<IJob>(new PerScopeLifetime());
            container.Register(z => new StdSchedulerFactory().GetScheduler());

            Config.Init(container.GetInstance<IScheduler>());

            Console.ReadKey();
        }
    }

    public class ScopedJob : IJob
    {
        private readonly IServiceContainer _container;
        private readonly Func<IServiceProvider> _factory;

        public ScopedJob(Func<IServiceProvider> factory, IServiceContainer container)
        {
            _factory = factory;
            _container = container;
        }

        public void Execute(IJobExecutionContext context)
        {
            using (_container.BeginScope())
            {
                var job = _factory.Invoke(_container.GetInstance<IServiceProvider>());
                job.Execute(context);
            }
        }
    }

    public class Job : IJob
    {
        public void Execute(IJobExecutionContext context)
        {
            Console.WriteLine("Job");
        }
    }

    public class Factory : IJobFactory
    {
        private readonly IServiceContainer _container;

        public Factory(IServiceContainer container)
        {
            _container = container;
        }

        public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler)
        {
            IJob Factory(IServiceProvider scope)
            {
                return (IJob)scope.GetService(bundle.JobDetail.JobType);
            }

            //return _provider.GetService(bundle.JobDetail.JobType) as IJob;
            return new ScopedJob(Factory, _container);
        }

        public void ReturnJob(IJob job)
        {
            Console.WriteLine("Return Job");
        }
    }

    public static class Config
    {
        public static void Init(IScheduler scheduler)
        {
            scheduler.ScheduleJob(
                JobBuilder.Create<Job>().Build(),
                TriggerBuilder.Create().WithSimpleSchedule(z => z.WithIntervalInSeconds(5).RepeatForever()).Build());

            scheduler.Start();
        }
    }
}

 

Revise this Paste

Your Name: Code Language: