Пример #1
1
 public QuartzService()
 {
     InitializeComponent();
     logger = LogManager.GetLogger(GetType());
     ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
     scheduler = schedulerFactory.GetScheduler();
 }
Пример #2
0
        static void Main(string[] args)
        {
            ISchedulerFactory sf = new StdSchedulerFactory();
            IScheduler sched = sf.GetScheduler();

            IScheduler sched1 = sf.GetScheduler();

            JobDetail job = new JobDetail("job1","group1",typeof(SimpleJob));

            //DateTime runtime = TriggerUtils.GetEvenMinuteDate(DateTime.UtcNow);//下一分钟

            //DateTime runtime = TriggerUtils.GetNextGivenSecondDate(null, 15);//15秒后

            //每一秒运行一次 重复十次 开始时间为now 结束时间为null
            //SimpleTrigger trigger = new SimpleTrigger("trigger1", "gropp1", "job1", "group1", DateTime.UtcNow, null, 10, TimeSpan.FromSeconds(10));

            SimpleTrigger trigger = new SimpleTrigger("trigger1",
                                "gropp1",
                                DateTime.UtcNow,
                                null,
                                SimpleTrigger.RepeatIndefinitely,
                                TimeSpan.FromSeconds(1));

            sched.ScheduleJob(job,trigger);

            LogManager.GetLogger(typeof(Program)).Info("开始循环,每10秒运行一次,重复10次");

            sched.Start();

            //Thread.Sleep(90 * 1000);
        }
Пример #3
0
 public JobEntrance()
 {
     ISchedulerFactory sf = new StdSchedulerFactory();
     _scheduler = sf.GetScheduler();
     var loggerFactory = new DefaultLoggerFactory();
     _logger = loggerFactory.GetLogger();
 }
Пример #4
0
 private void InitializeScheduling()
 {
     _log = LogManager.GetLogger(typeof(JobService));
     ISchedulerFactory sf = new StdSchedulerFactory();
     _sched = sf.GetScheduler();
     _log.Info("** Initialized **");
 }
Пример #5
0
        public JobSchedule()
        {
            var schedFact = new StdSchedulerFactory();

            sched = schedFact.GetScheduler();
            sched.Start();
        }
Пример #6
0
        protected override void OnStart(string[] args)
        {
            using (System.IO.StreamWriter sw = new System.IO.StreamWriter("E:\\log.txt", true))
            {
                sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "start.");
            }

            ISchedulerFactory schedFact = new StdSchedulerFactory();
            // get a scheduler
            IScheduler sched = schedFact.GetScheduler();
            sched.Start();

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create<HelloWorld>()
                .WithIdentity("myJob", "group1")
                .Build();

            //ITrigger trigger = TriggerBuilder.Create()
            //  .WithIdentity("myTrigger", "group1")
            //  .StartNow()
            //  .WithSimpleSchedule(x => x
            //      .WithIntervalInHours(1)
            //      .RepeatForever())
            //  .Build();
            ITrigger trigger = TriggerBuilder.Create()
            .WithIdentity("myTrigger", "group1")
            .WithCronSchedule("0/5 * * * * ?")
            .ForJob("myJob", "group1")
            .Build();
            sched.ScheduleJob(job, trigger);
        }
Пример #7
0
 private TaskManager()
 {
     // construct a scheduler factory
     ISchedulerFactory schedFact = new StdSchedulerFactory();
     // get a scheduler
     _sched = schedFact.GetScheduler();
 }
Пример #8
0
        protected override void OnStart(string[] args)
        {
            logger.Log(LogLevel.Info, String.Format("Starting Open Payments Processor"));

            // construct a scheduler factory
            ISchedulerFactory schedFact = new StdSchedulerFactory();

            IScheduler sched = schedFact.GetScheduler();
            Context ctx = new Context();

            JobDetail jobDetail = new JobDetail("myJob", null, typeof(ProcessOpenPaymentJob));

            Trigger trigger = TriggerUtils.MakeDailyTrigger(5, 00);

            trigger.StartTimeUtc = DateTime.UtcNow;
            trigger.Name = "myTrigger1";
            sched.ScheduleJob(jobDetail, trigger);

            try
            {
                logger.Log(LogLevel.Info, String.Format("Starting Scheduler"));
                sched.Start();
            }
            catch (Exception ex)
            {
                logger.Log(LogLevel.Info, String.Format("Exception Starting Scheduler {0}", ex.Message));
                throw;
            }
        }
Пример #9
0
        public void StartSample()
        {
            // construct a scheduler factory
            ISchedulerFactory schedFact = new StdSchedulerFactory();

            // get a scheduler
            IScheduler sched = schedFact.GetScheduler();
            sched.Start();

            // define the job and tie it to our HelloJob class
            JobDataMap newJobDataMap = new JobDataMap {{"myStateData", new List<DateTimeOffset>()}};

            IJobDetail job = JobBuilder.Create<StateJob>()
                .WithIdentity("myJob", "group1")
                .SetJobData(newJobDataMap)
                .Build();

            // Trigger the job to run now, and then every 5 seconds
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("myTrigger", "group1")
                .StartNow()
                .WithSimpleSchedule(x => x
                    .WithIntervalInSeconds(5)
                    .RepeatForever())
                .Build();

            sched.ScheduleJob(job, trigger);
        }
Пример #10
0
        public string DoHelloWorld()
        {
            // construct a scheduler factory
            ISchedulerFactory schedFact = new StdSchedulerFactory();

            // get a scheduler
            IScheduler sched = schedFact.GetScheduler();
            sched.Start();

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create<HelloJob>()
                .WithIdentity("myJob", "group1")
                .Build();

            // Trigger the job to run now, and then every 40 seconds
            ITrigger trigger = TriggerBuilder.Create()
              .WithIdentity("myTrigger", "group1")
              .StartNow()
              .WithSimpleSchedule(x => x
                  .WithIntervalInSeconds(5)
                  .RepeatForever())
              .Build();

            sched.ScheduleJob(job, trigger);
            return "NOOOOO, they're all gonna laugh at you!";
        }
Пример #11
0
 private Scheduler()
 {
     ISchedulerFactory schedFact = new StdSchedulerFactory();
     this._sched = schedFact.GetScheduler();
     // Start up the scheduler (nothing can actually run until the scheduler has been started)
     this._sched.Start();
 }
Пример #12
0
        public static void InitScheduler(String link)
        {
            if (rootPath != null)
                return;
            rootPath = link;
            ISchedulerFactory schedFact = new StdSchedulerFactory();
            Scheduler = schedFact.GetScheduler();
            Scheduler.Start();
            IJobDetail jobDetail = JobBuilder.Create<PhotoNotifyJob>().WithIdentity("PhotoNotificationJob").Build();
            jobDetail.JobDataMap.Add("path", rootPath);
            //Wystartuj jak najwczesniej, o godzinie 2:00 rano
            DateTime startAt = DateTime.Today;

            startAt = startAt.AddHours(2);
            if (startAt < DateTime.Now) //jesli juz minela godzina 2, wystartuj nastepnego dnia
                startAt = startAt.AddDays(1);

            ITrigger trigger2 = (ISimpleTrigger)TriggerBuilder.Create()
                                           .WithIdentity("trigger")
                                           .StartAt(startAt) // wystartuj scheduler o zadanej godzinie
                                           .WithSimpleSchedule(x => x.WithIntervalInHours(24).RepeatForever()) //odpalaj notyfikacje co 24h, bez limitu powtorzen
                                           .Build();
            DateTimeOffset ft = Scheduler.ScheduleJob(jobDetail, trigger2);
            System.Diagnostics.Debug.WriteLine(jobDetail.Key + " has been scheduled to run at: " + ft);
        }
Пример #13
0
        public void TestMethod1()
        {
            XmlConfigurator.Configure();

            log.Info("------- Initializing ----------------------");
            // First we must get a reference to a scheduler
            ISchedulerFactory sf = new StdSchedulerFactory();
            IScheduler sched = sf.GetScheduler();

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create<MyJob>()
                .WithIdentity("MyJob")
                .Build();

            // Trigger the job to run on the next round minute
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("MyTrigger")
                .WithCronSchedule("0 0/5 * * * ?")
                .Build();

            // Tell quartz to schedule the job using our trigger
            sched.ScheduleJob(job, trigger);

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            sched.Start();
            sched.Shutdown();
            Thread.Sleep(300 * 1000);
        }
        protected override void ConfigureBus(IInMemoryBusFactoryConfigurator configurator)
        {
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();
            _scheduler = schedulerFactory.GetScheduler();

            configurator.UseInMemoryScheduler();
        }
Пример #15
0
        public static IScheduler ConfigureQuartzJobs()
        {
            var properties = new NameValueCollection();
            properties["quartz.scheduler.instanceName"] = "ServerScheduler";

            // set thread pool info
            properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"] = "10";
            properties["quartz.threadPool.threadPriority"] = "Normal";

            // set remoting expoter
            properties["quartz.scheduler.proxy"] = "true";
            properties["quartz.scheduler.proxy.address"] = "tcp://localhost:555/QuartzScheduler";
            // construct a scheduler factory
            ISchedulerFactory schedFact = new StdSchedulerFactory();

            // get a scheduler
            IScheduler sched = schedFact.GetScheduler();
            sched.Start();

            //IJobDetail jobDetail = JobBuilder.Create<SimpleJob>()
            //    .WithIdentity("simpleJob", "simpleJobs")
            //    .RequestRecovery()
            //    .Build();

            //ITrigger trigger = TriggerBuilder.Create()
            //    .WithIdentity("simpleTrigger", "simpleTriggers")
            //    .StartNow()
            //    .WithSimpleSchedule(x => x.WithRepeatCount(4).WithIntervalInSeconds(10))
            //    .Build();

            //sched.ScheduleJob(jobDetail, trigger);

            return sched;
        }
Пример #16
0
        static void Start(IAppBuilder app) {

            // First, initialize Quartz.NET as usual. In this sample app I'll configure Quartz.NET by code.
            var schedulerFactory = new StdSchedulerFactory();
            var scheduler = schedulerFactory.GetScheduler();
            scheduler.Start();

            // I'll add some global listeners
            //scheduler.ListenerManager.AddJobListener(new GlobalJobListener());
            //scheduler.ListenerManager.AddTriggerListener(new GlobalTriggerListener());

            // A sample trigger and job
            var trigger = TriggerBuilder.Create()
                .WithIdentity("myTrigger")
                .WithSchedule(DailyTimeIntervalScheduleBuilder.Create()
                    .WithIntervalInSeconds(6))
                .StartNow()
                .Build();
            var job = new JobDetailImpl("myJob", null, typeof(HelloJob));
            scheduler.ScheduleJob(job, trigger);

            // A cron trigger and job
            var cron = TriggerBuilder.Create()
                .WithIdentity("myCronTrigger")
                .ForJob(job.Key)
                .WithCronSchedule("0/10 * * * * ?") // every 10 seconds
                .Build();

            scheduler.ScheduleJob(cron);

            // A dummy calendar
            //scheduler.AddCalendar("myCalendar", new DummyCalendar { Description = "dummy calendar" }, false, false);

            app.Use(QuartzNetWebConsole.Setup.Owin("/quartz/", () => scheduler));
        }
Пример #17
0
        static void Main(string[] args)
        {
            try
            {
                Console.Title = "QMail";
                Console.ForegroundColor = ConsoleColor.White;
                ISchedulerFactory sf = new StdSchedulerFactory();
                Scheduler = sf.GetScheduler();
                new TskInspectDetailJobTrigger();
                Scheduler.Start();

                for (var i = 0; i < 10; i++) {
                    Console.WriteLine();
                }

                Console.ForegroundColor = ConsoleColor.Yellow;

                Console.WriteLine("       ---------------------------------------------------");
                Console.WriteLine("       ...................QMail已启动......................");
                Console.WriteLine("       ...................请不要关闭此窗口.................");
                Console.WriteLine("       ---------------------------------------------------");
                for (var i = 0; i < 10; i++)
                {
                    Console.WriteLine();
                }
                Console.ReadLine();
            }
            catch (Exception e) {
                LogUtil.Logger.Error(e.Message);
            }
        }
Пример #18
0
        static void Main(string[] args)
        {
            //Create the scheduler factory
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

            //Ask the scheduler factory for a scheduler
            IScheduler scheduler = schedulerFactory.GetScheduler();

            //Start the scheduler so that it can start executing jobs
            scheduler.Start();

            // Create a job of Type WriteToConsoleJob
            IJobDetail job1 = JobBuilder.Create(typeof(DisallowConcurrentJob)).WithIdentity("DisallowConcurrentJob", "DisallowConcurrentJobGroup").Build();

            //Schedule this job to execute every second, a maximum of 10 times
            ITrigger trigger1 = TriggerBuilder.Create().WithSchedule(SimpleScheduleBuilder.RepeatSecondlyForTotalCount(10)).StartNow().WithIdentity("DisallowConcurrentJobTrigger", "DisallowConcurrentJobTriggerGroup").Build();
            scheduler.ScheduleJob(job1, trigger1);

            // Create a job of Type WriteToConsoleJob
            IJobDetail job2 = JobBuilder.Create(typeof(AllowConcurrentJob)).WithIdentity("AllowConcurrentJob", "AllowConcurrentJobGroup").Build();

            //Schedule this job to execute every second, a maximum of 10 times
            ITrigger trigger2 = TriggerBuilder.Create().WithSchedule(SimpleScheduleBuilder.RepeatSecondlyForTotalCount(10)).StartNow().WithIdentity("AllowConcurrentJobTrigger", "AllowConcurrentJobTriggerGroup").Build();
            scheduler.ScheduleJob(job2, trigger2);

            //Wait for a key press. If we don't wait the program exits and the scheduler gets destroyed
            Console.ReadKey();

            //A nice way to stop the scheduler, waiting for jobs that are running to finish
            scheduler.Shutdown(true);
        }
Пример #19
0
 static void Main(string[] args)
 {
     var factory = new StdSchedulerFactory();
     var scheduler = factory.GetScheduler();
     scheduler.Start();
     while (!scheduler.IsStarted)
     {
         Console.WriteLine("Waiting for scheduler to start.");
         Thread.Sleep(1000);
     }
     Console.WriteLine("IsStarted={0}", scheduler.IsStarted);
     Console.WriteLine("SchedulerInstanceId={0}", scheduler.SchedulerInstanceId);
     Console.WriteLine("SchedulerName={0}", scheduler.SchedulerName);
     Console.WriteLine("The scheduler is running. Press any key to stop");
     Console.ReadKey();
     Console.WriteLine("Shutting down scheduler");
     scheduler.Shutdown(false);
     while (!scheduler.IsShutdown)
     {
         Console.WriteLine("Waiting for scheduler to shutdown.");
         Thread.Sleep(1000);
     }
     Console.WriteLine("IsShutdown={0}", scheduler.IsShutdown);
     Console.WriteLine("The scheduler has been shutdown.");
 }
Пример #20
0
 static TaskPool()
 {
     _taskpool = new TaskPool();
     ISchedulerFactory sf = new StdSchedulerFactory();
     _ische = sf.GetScheduler();
     _ische.Start();
 }
Пример #21
0
        public void Run()
        {
            ILog log = LogManager.GetLogger(typeof(SimpleExample));

            log.Info("------- Initializing ----------------------");

            ISchedulerFactory sf = new StdSchedulerFactory();
            IScheduler sched = sf.GetScheduler();

            log.Info("------- Initialization Complete -----------");

            log.Info("------- Scheduling Jobs -------------------");

            DateTime runTime = TriggerUtils.GetEvenMinuteDate(DateTime.UtcNow);
            JobDetail job = new JobDetail("job1", "group1", typeof(HelloJob));

            SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1", runTime);
            sched.ScheduleJob(job, trigger);

            sched.Start();

            log.Info("------- Started Scheduler -----------------");

            // wait long enough so that the scheduler as an opportunity to 
            // run the job!
            log.Info("------- Waiting 90 seconds... -------------");

            // wait 90 seconds to show jobs
            Thread.Sleep(90 * 1000);

            // shut down the scheduler
            log.Info("------- Shutting Down ---------------------");
            sched.Shutdown(true);
            log.Info("------- Shutdown Complete -----------------");
        }
Пример #22
0
        private void CreateSchedule(int jobId,TaskData taskData,DateTimeOffset runTime)
        {
            ISchedulerFactory sf = new StdSchedulerFactory();
            IScheduler sched = sf.GetScheduler();

            // define the job
            IJobDetail job;
            if (jobId < 0)
            {
                job = JobBuilder.Create<QueryJob>()
                .WithIdentity("jobQuery" + jobId, "groupBackup")
                .Build();
            }
            else
            {
                job = JobBuilder.Create<BackupJob>()
                .WithIdentity("jobBackup" + jobId, "groupBackup")
                .Build();
            }

            // Trigger the job
            ITrigger trigger = TriggerBuilder.Create()
            .UsingJobData("date", taskData.Date.ToString("yyyyMMddHHmm"))
                //.UsingJobData("time", taskData.Date.Hour+":"+taskData.Date.Minute+":"+taskData.Date.Second)
            .WithIdentity("triggerBackup" + jobId, "groupBackup")
            .StartAt(runTime)
            .Build();

            // Tell quartz to schedule the job using our trigger
            sched.ScheduleJob(job, trigger);

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            sched.Start();
        }
Пример #23
0
 static Scheduler()
 {
     ISchedulerFactory schedFact = new StdSchedulerFactory();
     QuartzSheduler = schedFact.GetScheduler();
     QuartzSheduler.Start();
     items = new List<Item>();
 }
Пример #24
0
 public Task TestFactoryCanBeUsedWithEmptyProperties()
 {
     var props = new NameValueCollection();
     props["quartz.serializer.type"] = TestConstants.DefaultSerializerType;
     StdSchedulerFactory factory = new StdSchedulerFactory(props);
     return factory.GetScheduler();
 }
 /// <summary>
 /// 静态初始化
 /// </summary>
 static TaskPoolManager()
 {
     _taskpoolmanager = new TaskPoolManager();
     ISchedulerFactory sf = new StdSchedulerFactory();
     _sched = sf.GetScheduler();
     _sched.Start();
 }
        public void StartTrigger()
        {
            // construct a scheduler factory
            ISchedulerFactory schedFact = new StdSchedulerFactory();

            // get a scheduler
            _sched = schedFact.GetScheduler();

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create<QuartzJob>()
                .WithIdentity("job_" + datasetConfig.Name, "group1")
                .Build();


            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            // Trigger the job to run on the next round minute
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger_" + datasetConfig.Name, "group1")
                .WithCronSchedule(datasetConfig.CronTab)
                //.StartAt(runTime)
                .Build();

            job.JobDataMap["CallbackMethod"] = new Action(TriggerCallback);

            _sched.ScheduleJob(job, trigger);
            _sched.Start();
        }
Пример #27
0
        static void Main(string[] args)
        {
            //  System.Threading.Thread.CurrentThread.Priority = System.Threading.ThreadPriority.Lowest;

            Process thisProc = Process.GetCurrentProcess();
            thisProc.PriorityClass = ProcessPriorityClass.Idle;

                log4net.Config.XmlConfigurator.Configure();

                // construct a scheduler factory
                ISchedulerFactory schedFact = new StdSchedulerFactory();

                //  double v = double.Parse("603,0");

                //IJobDetail jobDetail1 = JobBuilder.Create(typeof(Quartz.Server.Jobs.SendEmailJob))
                // .WithIdentity("job1", "group1")
                //.RequestRecovery(true)
                // .Build();

                //ITrigger trigger1 = TriggerBuilder.Create()
                //    .WithIdentity("trigger1", "group1")
                //    .WithCronSchedule(/*"0/60 * * * * ?"*/"*/30 * * * * ?")//каждые 30 секунд
                //    .Build();

                // get a scheduler
                IScheduler sched = schedFact.GetScheduler();
                // sched.ScheduleJob(jobDetail1, trigger1);
                sched.Start();
        }
Пример #28
0
        public static void Main(string[] args)
        {
            //            XmlConfigurator.Configure();

               var properties = new NameValueCollection();
               properties["quartz.scheduler.instanceName"] = "ServerScheduler";

            // set thread pool info
            properties["quartz.threadPool.threadCount"] = "0";

            // set remoting expoter
            properties["quartz.scheduler.proxy"] = "true";
            properties["quartz.scheduler.proxy.address"] = "tcp://localhost:555/QuartzScheduler";

            var scheduleFactory = new StdSchedulerFactory(properties);

            scheduler = scheduleFactory.GetScheduler();
            var md = scheduler.GetMetaData();
            scheduler.Start();

            IJobDetail job = JobBuilder.Create<Jobs.SimpleJob>().Build();

            ITrigger jobTrigger = new SimpleTriggerImpl("TenSecondTrigger", 20, new TimeSpan(0, 0, 0, 5));

            //Periodic scheduling
            scheduler.ScheduleJob(job,jobTrigger);

            //Trigger a job from elsewhere without a trigger for one time
            var jobKey = job.Key;
            var jobDataMap = job.JobDataMap;
            scheduler.TriggerJob(jobKey,jobDataMap);
        }
        protected void Application_Start(object sender, EventArgs e)
        {
            // First, initialize Quartz.NET as usual. In this sample app I'll configure Quartz.NET by code.
            var schedulerFactory = new StdSchedulerFactory();
            var scheduler = schedulerFactory.GetScheduler();
            scheduler.Start();

            // This tells the QuartzNetWebConsole what scheduler to use
            Setup.Scheduler = () => scheduler;

            // This adds an logger to the QuartzNetWebConsole. It's optional.
            var partialQuartzConsoleUrl = string.Format("http://{0}:{1}/quartz/", Context.Request.Url.Host, Context.Request.Url.Port);
            Setup.Logger = new MemoryLogger(1000, partialQuartzConsoleUrl);

            // I'll add some global listeners
            scheduler.AddGlobalJobListener(new GlobalJobListener());
            scheduler.AddGlobalTriggerListener(new GlobalTriggerListener());

            // A sample trigger and job
            var trigger = TriggerUtils.MakeSecondlyTrigger(6);
            trigger.StartTimeUtc = DateTime.UtcNow;
            trigger.Name = "myTrigger";
            scheduler.ScheduleJob(new JobDetail("myJob", null, typeof(HelloJob)), trigger);

            // A cron trigger and job
            var cron = new CronTrigger("myCronTrigger") {
                CronExpression = new CronExpression("0/10 * * * * ?"), // every 10 seconds
                JobName = "myJob",
            };
            scheduler.ScheduleJob(cron);

            // A dummy calendar
            scheduler.AddCalendar("myCalendar", new DummyCalendar {Description = "dummy calendar"}, false, false);
        }
Пример #30
0
        protected void Application_Start()
        {
            ValueProviderFactories.Factories.Add(new JsonValueProviderFactory()); // Depends on MVC2Futures library to make MVC ver2 controllers to accept JSON serialized objects
            log4net.Config.XmlConfigurator.Configure();
            AreaRegistration.RegisterAllAreas();
            RegisterRoutes(RouteTable.Routes);

            //TODO Protect Quartz from getting recycled. #9
            ISchedulerFactory schedFact = new StdSchedulerFactory();
            // get a scheduler
            IScheduler sched = schedFact.GetScheduler();

            // construct job info
            JobDetail jobDetail = new JobDetail("mySendMailJob", typeof(EmailJob));
            // fire every minute to check for queued e-mail messages in the db
            Trigger trigger = TriggerUtils.MakeMinutelyTrigger(1);
            trigger.Name = "mySendMailTrigger";
            // schedule the job for execution
            sched.ScheduleJob(jobDetail, trigger);
            sched.Start();
            log4net.ILog log = log4net.LogManager.GetLogger(typeof(MvcApplication));
            log.Info("Quartz Queue started! Application Started!");

            //To flush logger buffer immediatley if not configured in the config file
            //foreach (IAppender appender in log.Logger.Repository.GetAppenders())
            //{
            //    var buffered = appender as BufferingAppenderSkeleton;
            //    if (buffered != null)
            //    {
            //        buffered.Flush();
            //    }
            //}
        }
Пример #31
0
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new ConsoleLogFactory(debugEnabled: true);

            var jwtprovider = new JwtAuthProviderReader
            {
                HashAlgorithm = "RS256",
                PublicKeyXml  = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_JWT_PUBLIC_KEY_XML),
#if (DEBUG)
                RequireSecureConnection = false,
                //EncryptPayload = true,
#endif
            };

            this.Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                             new IAuthProvider[] {
                jwtprovider,
            }));

#if (DEBUG)
            SetConfig(new HostConfig {
                DebugMode = true
            });
#endif
            SetConfig(new HostConfig {
                DefaultContentType = MimeTypes.Json
            });



            RabbitMqMessageFactory rabitFactory = new RabbitMqMessageFactory();
            rabitFactory.ConnectionFactory.UserName    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_USER);
            rabitFactory.ConnectionFactory.Password    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_PASSWORD);
            rabitFactory.ConnectionFactory.HostName    = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_HOST);
            rabitFactory.ConnectionFactory.Port        = Convert.ToInt32(Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_PORT));
            rabitFactory.ConnectionFactory.VirtualHost = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_RABBIT_VHOST);

            var mqServer = new RabbitMqServer(rabitFactory);

            mqServer.RetryCount = 1;

            mqServer.RegisterHandler <ScheduleRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <DeleteJobRequest>(base.ExecuteMessage);
            mqServer.RegisterHandler <RescheduleRequest>(base.ExecuteMessage);

            mqServer.Start();

            container.AddScoped <IMessageProducer, RabbitMqProducer>(serviceProvider =>
            {
                return(mqServer.CreateMessageProducer() as RabbitMqProducer);
            });

            container.AddScoped <IMessageQueueClient, RabbitMqQueueClient>(serviceProvider =>
            {
                return(mqServer.CreateMessageQueueClient() as RabbitMqQueueClient);
            });

            //****************SCHEDULER********************
            string conn = string.Format("Server = {0}; Database = {1}; Uid = {2}; Pwd = {3}; Trust Server Certificate=true; Port= {4}; Use SSL Stream=true; SSL Mode=Require;",
                                        Environment.GetEnvironmentVariable(EnvironmentConstants.EB_INFRA_DB_SERVER),
                                        Environment.GetEnvironmentVariable(EnvironmentConstants.EB_INFRA_DBNAME),
                                        Environment.GetEnvironmentVariable(EnvironmentConstants.EB_INFRA_DB_RW_USER),
                                        Environment.GetEnvironmentVariable(EnvironmentConstants.EB_INFRA_DB_RW_PASSWORD),
                                        Environment.GetEnvironmentVariable(EnvironmentConstants.EB_INFRA_DB_PORT));
            var properties = new NameValueCollection
            {
                ["quartz.serializer.type"]                  = "json",
                ["quartz.scheduler.instanceName"]           = "DotnetCoreScheduler",
                ["quartz.scheduler.instanceId"]             = "instance_one",
                ["quartz.threadPool.type"]                  = "Quartz.Simpl.SimpleThreadPool, Quartz",
                ["quartz.threadPool.threadCount"]           = "5",
                ["quartz.jobStore.misfireThreshold"]        = "60000",
                ["quartz.jobStore.type"]                    = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz",
                ["quartz.jobStore.useProperties"]           = "true",
                ["quartz.jobStore.dataSource"]              = "myDS",
                ["quartz.jobStore.tablePrefix"]             = "QRTZ_",
                ["quartz.jobStore.driverDelegateType"]      = "Quartz.Impl.AdoJobStore.PostgreSQLDelegate, Quartz",
                ["quartz.dataSource.myDS.provider"]         = "Npgsql ",
                ["quartz.dataSource.myDS.connectionString"] = conn
            };


            StdSchedulerFactory factory   = new Quartz.Impl.StdSchedulerFactory(properties);
            IScheduler          scheduler = factory.GetScheduler().Result;
            scheduler.Start().Wait();

            container.AddScoped <IScheduler>(serviceProvider =>
            {
                return(scheduler);
            });

            string env = Environment.GetEnvironmentVariable(EnvironmentConstants.ASPNETCORE_ENVIRONMENT);

            var redisServer   = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_SERVER);
            var redisPassword = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_PASSWORD);
            var redisPort     = Environment.GetEnvironmentVariable(EnvironmentConstants.EB_REDIS_PORT);

            RedisClient client = null;
            //if (env == "Staging")
            //{
            //    client = new RedisClient(redisServer, Convert.ToInt32(redisPort));
            //}
            //else
            //{
            client = new RedisClient(string.Format("redis://{0}@{1}:{2}", redisPassword, redisServer, redisPort));
            //}
            //Setting Assembly version in Redis
            AssemblyName assembly = Assembly.GetExecutingAssembly().GetName();
            String       version  = assembly.Name.ToString() + " - " + assembly.Version.ToString();
            client.Set("SchedulerAssembly", version);

            this.GlobalRequestFilters.Add((req, res, requestDto) =>
            {
                ILog log = LogManager.GetLogger(GetType());

                log.Info("In GlobalRequestFilters");
                try
                {
                    log.Info("In Try");
                    if (requestDto != null)
                    {
                        log.Info("In Auth Header");
                        var auth = req.Headers[HttpHeaders.Authorization];
                        if (string.IsNullOrEmpty(auth))
                        {
                            res.ReturnAuthRequired();
                        }
                        else
                        {
                            if (req.Headers[CacheConstants.RTOKEN] != null)
                            {
                                Resolve <IEbServerEventClient>().AddAuthentication(req);
                            }
                            var jwtoken = new JwtSecurityToken(auth.Replace("Bearer", string.Empty).Trim());
                            foreach (var c in jwtoken.Claims)
                            {
                                if (c.Type == "cid" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add(CoreConstants.SOLUTION_ID, c.Value);
                                    if (requestDto is IEbSSRequest)
                                    {
                                        (requestDto as IEbSSRequest).SolnId = c.Value;
                                    }
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).SolnId = c.Value;
                                    }
                                    continue;
                                }
                                if (c.Type == "uid" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("UserId", Convert.ToInt32(c.Value));
                                    if (requestDto is IEbSSRequest)
                                    {
                                        (requestDto as IEbSSRequest).UserId = Convert.ToInt32(c.Value);
                                    }
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).UserId = Convert.ToInt32(c.Value);
                                    }
                                    continue;
                                }
                                if (c.Type == "wc" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("wc", c.Value);
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).WhichConsole = c.Value.ToString();
                                    }
                                    continue;
                                }
                                if (c.Type == "sub" && !string.IsNullOrEmpty(c.Value))
                                {
                                    RequestContext.Instance.Items.Add("sub", c.Value);
                                    if (requestDto is EbServiceStackAuthRequest)
                                    {
                                        (requestDto as EbServiceStackAuthRequest).UserAuthId = c.Value.ToString();
                                    }
                                    continue;
                                }
                            }
                            log.Info("Req Filter Completed");
                        }
                    }
                }
                catch (Exception e)
                {
                    log.Info("ErrorStackTraceNontokenServices..........." + e.StackTrace);
                    log.Info("ErrorMessageNontokenServices..........." + e.Message);
                    log.Info("InnerExceptionNontokenServices..........." + e.InnerException);
                }
            });
        }
Пример #32
0
        /// <summary>
        /// Returns a handle to the default Scheduler, creating it if it does not
        /// yet exist.
        /// </summary>
        /// <seealso cref="Initialize()">
        /// </seealso>
        public static IScheduler GetDefaultScheduler()
        {
            StdSchedulerFactory fact = new StdSchedulerFactory();

            return(fact.GetScheduler());
        }