示例#1
0
        private void SyncSuningDataJob(IScheduler scheduler, System.Collections.IDictionary param)
        {
            JobDetail job = scheduler.GetJobDetail("SNExpressJob", "Jinher.AMP.BTP.Job");

            job = new JobDetail("SNExpressJob", "Jinher.AMP.BTP.Job", typeof(SNExpressJob));
            job.JobDataMap.PutAll(param);

            DateTime      start   = DateTime.UtcNow;
            SimpleTrigger trigger = new SimpleTrigger("SNExpressJobTrigger", "Jinher.AMP.BTP.Job", start, null,
                                                      Jinher.JAP.Job.Engine.SimpleTrigger.RepeatIndefinitely, TimeSpan.FromHours(3));

            trigger.Description = "SNExpressJob触发器";
            //把创建的任务和触发器注册到调度器中
            scheduler.ScheduleJob(job, trigger);



            JobDetail job1 = scheduler.GetJobDetail("SNOrderJob", "Jinher.AMP.BTP.Job");

            job1 = new JobDetail("SNOrderJob", "Jinher.AMP.BTP.Job", typeof(SNExpressJob));
            job1.JobDataMap.PutAll(param);

            DateTime      start1   = DateTime.UtcNow;
            SimpleTrigger trigger1 = new SimpleTrigger("SNOrderJobTrigger", "Jinher.AMP.BTP.Job", start1, null,
                                                       Jinher.JAP.Job.Engine.SimpleTrigger.RepeatIndefinitely, TimeSpan.FromMinutes(5));

            trigger.Description = "SNOrderJob触发器";
            //把创建的任务和触发器注册到调度器中
            scheduler.ScheduleJob(job1, trigger1);
        }
示例#2
0
        /// <summary>
        /// 全量同步严选商品价格和库存
        /// </summary>
        /// <param name="scheduler"></param>
        /// <param name="param"></param>
        private void SyncAllYXPriceJob(IScheduler scheduler, System.Collections.IDictionary param)
        {
            JobDetail job1 = scheduler.GetJobDetail("YXSyncAllPriceJob1", "Jinher.AMP.BTP.Job");

            job1 = new JobDetail("YXSyncAllPriceJob1", "Jinher.AMP.BTP.Job", typeof(YXSyncAllPriceJob));
            job1.JobDataMap.PutAll(param);

            //北京时间领先UTC 8个小时
            //每天10点运行
            SimpleTrigger trigger1 = new SimpleTrigger("YXSyncAllPriceJobTrigger1", "Jinher.AMP.BTP.Job", DateTime.UtcNow.Date.AddDays(1).AddHours(2), null,
                                                       Jinher.JAP.Job.Engine.SimpleTrigger.RepeatIndefinitely, TimeSpan.FromHours(24));

            trigger1.Description = "YXSyncAllPriceJobTrigger1触发器";
            scheduler.ScheduleJob(job1, trigger1);

            JobDetail job2 = scheduler.GetJobDetail("YXSyncAllPriceJob2", "Jinher.AMP.BTP.Job");

            job2 = new JobDetail("YXSyncAllPriceJob2", "Jinher.AMP.BTP.Job", typeof(YXSyncAllPriceJob));
            job2.JobDataMap.PutAll(param);

            //每天15.30点运行
            SimpleTrigger trigger2 = new SimpleTrigger("YXSyncAllPriceJobTrigger2", "Jinher.AMP.BTP.Job", DateTime.UtcNow.Date.AddDays(1).AddHours(7.5), null,
                                                       Jinher.JAP.Job.Engine.SimpleTrigger.RepeatIndefinitely, TimeSpan.FromHours(24));

            trigger2.Description = "YXSyncAllPriceJobTrigger2触发器";
            scheduler.ScheduleJob(job2, trigger2);
        }
        public QueryResponse Post([FromBody] SimpleTrigger model)
        {
            Logger.InfoFormat("Entered TriggersController.Post(). Name = {0}", model.Name);

            var response = new QueryResponse {
                Valid = true
            };

            var authorizedJobGroups = _permissionsHelper.GetAuthorizedJobGroups().ToList();

            if (authorizedJobGroups.Contains(model.Group) || authorizedJobGroups.Contains("*"))
            {
                try
                {
                    _schedulerCore.ScheduleTrigger(model);
                }
                catch (Exception ex)
                {
                    response.Valid  = false;
                    response.Errors = new List <Error>
                    {
                        new Error
                        {
                            Code    = "ErrorSchedulingTrigger",
                            Type    = "Server",
                            Message = string.Format("Error scheduling trigger {0}", ex.Message)
                        }
                    };
                }

                return(response);
            }
            throw new HttpResponseException(HttpStatusCode.Unauthorized);
        }
示例#4
0
        public void TestRescheduleJob_SchedulerListenersCalledOnReschedule()
        {
            const string TriggerName  = "triggerName";
            const string TriggerGroup = "triggerGroup";
            const string JobName      = "jobName";
            const string JobGroup     = "jobGroup";

            ISchedulerFactory sf           = new StdSchedulerFactory();
            IScheduler        scheduler    = sf.GetScheduler();
            DateTime          startTimeUtc = DateTime.UtcNow.AddSeconds(2);
            JobDetail         jobDetail    = new JobDetail(JobName, JobGroup, typeof(NoOpJob));
            SimpleTrigger     jobTrigger   = new SimpleTrigger(TriggerName, TriggerGroup, JobName, JobGroup, startTimeUtc, null, 1, TimeSpan.FromMilliseconds(1000));

            MockRepository     mockery  = new MockRepository();
            ISchedulerListener listener = (ISchedulerListener)mockery.CreateMock(typeof(ISchedulerListener));

            scheduler.ScheduleJob(jobDetail, jobTrigger);
            // add listener after scheduled
            scheduler.AddSchedulerListener(listener);

            // expect unschedule and schedule
            listener.JobUnscheduled(TriggerName, TriggerGroup);
            listener.JobScheduled(jobTrigger);

            mockery.ReplayAll();

            // act
            scheduler.RescheduleJob(TriggerName, TriggerGroup, jobTrigger);

            // verify
            mockery.VerifyAll();
        }
        public void TestScheduleTriggerWithNoJobDataMapSavesEmptyDataOnTrigger()
        {
            // Arrange
            Scheduler.Shutdown();
            Scheduler.Initialize((config =>
            {
                config.EnableWebApiSelfHost = false;
                config.EnableAuditHistory = false;
            }));
            IPersistanceStore persistanceStore = new InMemoryStore();

            _schedulerCore = new SchedulerCore(Scheduler.Instance(), persistanceStore);

            const string jobName     = "Job1";
            const string jobGroup    = "Group1";
            const string triggerName = "Trigger1";

            _schedulerCore.CreateJob(jobName, jobGroup, typeof(NoOpJob), new Dictionary <string, object>(), string.Empty);

            var simpleTrigger = new SimpleTrigger
            {
                RepeatCount    = 1,
                RepeatInterval = new TimeSpan(0, 1, 0, 0),
                JobName        = jobName,
                JobGroup       = jobGroup,
                Name           = triggerName
            };

            // Act
            var result = _schedulerCore.ScheduleTrigger(simpleTrigger);

            // Assert
            Assert.Equal(triggerName, Scheduler.Instance().GetTrigger(new TriggerKey(triggerName)).Key.Name);
            Assert.Equal(0, Scheduler.Instance().GetTrigger(new TriggerKey(triggerName)).JobDataMap.Count);
        }
        public void TestAddTriggerSetsStartTime()
        {
            SimpleTrigger st = new SimpleTrigger("foo", "bar", DateTime.MinValue);

            bundle.AddTrigger(st);
            Assert.AreNotEqual(DateTime.MinValue, st.StartTimeUtc);
        }
示例#7
0
        public QueryResponse Post([FromBody] SimpleTrigger model)
        {
            Logger.InfoFormat("Entered TriggersController.Post(). Name = {0}", model.Name);

            var response = new QueryResponse {
                Valid = true
            };

            try
            {
                _schedulerCore.ScheduleTrigger(model);
            }
            catch (Exception ex)
            {
                response.Valid  = false;
                response.Errors = new List <Error>
                {
                    new Error
                    {
                        Code    = "ErrorSchedulingTrigger",
                        Type    = "Server",
                        Message = string.Format("Error scheduling trigger {0}", ex.Message)
                    }
                };
            }

            return(response);
        }
示例#8
0
        private void ProcessSeedMonitorForking(IScheduler oSch)
        {
            // Get all the registered seed IP from the app configuration file
            List <AppConfig.ContentDeployJob.OfficalSeedWeb> listSeedIp = AppConfig.ContentDeployJob.OfficalSeedWebList;

            // Enumerate all the seed web and schedule the new trigger / job pair accordingly
            AppConfig.ContentDeployJob.OfficalSeedWebList.ForEach(oSeedWeb =>
            {
                // Create and initialize the content monitor job & the trigger
                JobDetail oJob = new JobDetail(
                    oSeedWeb.IP,
                    SeedMonitorConstants.SeedMonitorGroupName,
                    typeof(SeedMonitorJob));
                SimpleTrigger oTrigger = new SimpleTrigger(
                    oSeedWeb.IP,
                    SeedMonitorConstants.SeedMonitorGroupName,
                    -1, TimeSpan.FromSeconds(SeedMonitorConstants.SeedMonitorPeriodSec));

                // Add the seed web to the job data map
                // There is no concurrency issue here since the data map entry won't be
                // updated when the job is running
                oJob.JobDataMap[SeedMonitorJobDataMapConstants.OfficalSeedWeb] = oSeedWeb;
                oJob.Durable      = false;
                oTrigger.Priority = 1; // Low priority
                oTrigger.JobName  = oSeedWeb.IP;
                oTrigger.JobGroup = SeedMonitorConstants.SeedMonitorGroupName;
                oSch.ScheduleJob(oJob, oTrigger);
                // ************************************************************************************
                log.DebugFormat("Start to monitor the seed: {0}", oSeedWeb.IP);
                // ************************************************************************************
            });
        }
示例#9
0
        public static void Quartz_1_0_Main()
        {
            //每隔一段时间执行任务
            ISchedulerFactory sf    = new StdSchedulerFactory();
            IScheduler        sched = sf.GetScheduler();
            //括号里是为实现了IJob接口的类
            JobDetail job = new JobDetail("job1", "group1", typeof(MyJog));
            //5秒后开始第一次运行
            DateTime ts = TriggerUtils.GetNextGivenSecondDate(null, 5);

            //每隔9秒执行一次
            //TimeSpan interval = TimeSpan.FromSeconds(9);
            //时间段,每隔1小时执行一次
            //TimeSpan interval = TimeSpan.FromHours(1);

            //每隔24小时执行一次
            TimeSpan interval = TimeSpan.FromHours(24);
            Trigger  trigger  = new SimpleTrigger("trigger1", "group1", "job1", "group1", ts, null,
                                                  //每若干小时运行一次,小时间隔由appsettings中的IndexIntervalHour参数指定
                                                  SimpleTrigger.RepeatIndefinitely, interval);


            //Quartz比Timer更加精准,
            sched.AddJob(job, true);
            sched.ScheduleJob(trigger);
            sched.Start();
            //要关闭任务定时则需要sched.Shutdown(true)
        }
示例#10
0
        public void TestScheduleTriggerWithJobDataMapSavesDataOnTrigger()
        {
            // Arrange
            Scheduler.Shutdown();
            Scheduler.Initialize((config =>
            {
                config.EnableWebApiSelfHost = false;
                config.EnableAuditHistory = false;
            }));
            IPersistanceStore persistanceStore = new InMemoryStore();
            _schedulerCore = new SchedulerCore(Scheduler.Instance(), persistanceStore);

            const string jobName = "Job1";
            const string jobGroup = "Group1";
            const string triggerName = "Trigger1";

            _schedulerCore.CreateJob(jobName, jobGroup, typeof(NoOpJob), new Dictionary<string, object>(), string.Empty);

            var simpleTrigger = new SimpleTrigger
            {
                RepeatCount = 1,
                RepeatInterval = new TimeSpan(0, 1, 0, 0),
                JobName = jobName,
                JobGroup = jobGroup,
                Name = triggerName,
                JobDataMap = new Dictionary<string, object> {{"Key1", "Value1"}}
            };

            // Act
            var result = _schedulerCore.ScheduleTrigger(simpleTrigger);

            // Assert
            Assert.Equal(triggerName, Scheduler.Instance().GetTrigger(new TriggerKey(triggerName)).Key.Name);
            Assert.Equal("Value1", Scheduler.Instance().GetTrigger(new TriggerKey(triggerName)).JobDataMap.GetString("Key1"));
        }
示例#11
0
        public void TestDifferentPriority()
        {
            IScheduler sched = new StdSchedulerFactory().GetScheduler();

            DateTime n   = DateTime.UtcNow;
            DateTime cal = new DateTime(n.Year, n.Month, n.Day, n.Hour, n.Minute, 1, n.Millisecond);

            Trigger trig1 = new SimpleTrigger("T1", null, cal);

            trig1.Priority = 5;

            Trigger trig2 = new SimpleTrigger("T2", null, cal);

            trig2.Priority = 10;

            JobDetail jobDetail = new JobDetail("JD", null, typeof(TestJob));

            sched.ScheduleJob(jobDetail, trig1);

            trig2.JobName = jobDetail.Name;
            sched.ScheduleJob(trig2);

            sched.Start();

            Thread.Sleep(2000);

            Assert.AreEqual("T2T1", result.ToString());

            sched.Shutdown();
        }
示例#12
0
        /// <summary>
        /// Schedule plugin to execute 3 seconds in the future and then 3 more times with 3 second intervals
        /// </summary>
        private static void SchedulePluginWithSimpleTrigger()
        {
            var trigger = new SimpleTrigger
            {
                Name           = "MyPluginTestTrigger",
                Group          = "DEFAULT",
                JobName        = "MyAssemblyPluginJob",
                JobGroup       = "MyJobGroup",
                StartDateTime  = DateTime.Now.AddSeconds(3),
                RepeatCount    = 3,
                RepeatInterval = new TimeSpan(0, 0, 0, 3)
            };

            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(Url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                var    response = client.PostAsJsonAsync("api/simpleTriggers", trigger).Result;
                string result   = response.Content.ReadAsStringAsync().Result;

                if (result != null)
                {
                    Console.WriteLine(result);
                }
            }
        }
        public void TestAddTriggerAddsTrigger()
        {
            SimpleTrigger st = new SimpleTrigger("foo", "bar", DateTime.MinValue);

            bundle.AddTrigger(st);
            Assert.AreEqual(1, bundle.Triggers.Count);
        }
        public void TestAddTriggerListener()
        {
            string[] listenerNames = new string[] { "X", "A", "B" };

            // Verify that a HashSet shuffles order, so we know that order test
            // below is actually testing something
            HashSet hashSet = new HashSet(listenerNames);

            Assert.IsFalse(new ArrayList(listenerNames).Equals(new ArrayList(hashSet)));

            SimpleTrigger simpleTrigger = new SimpleTrigger();

            for (int i = 0; i < listenerNames.Length; i++)
            {
                simpleTrigger.AddTriggerListener(listenerNames[i]);
            }

            // Make sure order was maintained
            TestUtil.AssertCollectionEquality(new ArrayList(listenerNames),
                                              new ArrayList(simpleTrigger.TriggerListenerNames));

            // Make sure uniqueness is enforced
            for (int i = 0; i < listenerNames.Length; i++)
            {
                try
                {
                    simpleTrigger.AddTriggerListener(listenerNames[i]);
                    Assert.Fail();
                }
                catch (ArgumentException)
                {
                }
            }
        }
示例#15
0
        public void TestTriggerStates()
        {
            Trigger trigger =
                new SimpleTrigger("trigger1", "triggerGroup1", fJobDetail.Name, fJobDetail.Group,
                                  DateTime.Now.AddSeconds(100), DateTime.Now.AddSeconds(200), 2, TimeSpan.FromSeconds(2));

            trigger.ComputeFirstFireTimeUtc(null);
            Assert.AreEqual(TriggerState.None, fJobStore.GetTriggerState(null, trigger.Name, trigger.Group));
            fJobStore.StoreTrigger(null, trigger, false);
            Assert.AreEqual(TriggerState.Normal, fJobStore.GetTriggerState(null, trigger.Name, trigger.Group));

            fJobStore.PauseTrigger(null, trigger.Name, trigger.Group);
            Assert.AreEqual(TriggerState.Paused, fJobStore.GetTriggerState(null, trigger.Name, trigger.Group));

            fJobStore.ResumeTrigger(null, trigger.Name, trigger.Group);
            Assert.AreEqual(TriggerState.Normal, fJobStore.GetTriggerState(null, trigger.Name, trigger.Group));

            trigger = fJobStore.AcquireNextTrigger(null,
                                                   trigger.GetNextFireTimeUtc().Value.AddSeconds(10));
            Assert.IsNotNull(trigger);
            fJobStore.ReleaseAcquiredTrigger(null, trigger);
            trigger = fJobStore.AcquireNextTrigger(null,
                                                   trigger.GetNextFireTimeUtc().Value.AddSeconds(10));
            Assert.IsNotNull(trigger);
            Assert.IsNull(fJobStore.AcquireNextTrigger(null,
                                                       trigger.GetNextFireTimeUtc().Value.AddSeconds(10)));
        }
示例#16
0
        public void StartQuartz()
        {
            try
            {
                LogHelper.Info("QuartzManaer执行");


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


                //====================每隔120分钟执行任务===================
                JobDetail jobShowGoods      = new JobDetail("job1", "group1", typeof(QuartzShowGoodsJob));           //IndexJob为实现了IJob接口的类
                DateTime  tsShowGoods       = TriggerUtils.GetNextGivenSecondDate(null, 0);                          //7天以后第一次运行
                TimeSpan  intervaShowGoods  = TimeSpan.FromMinutes(5);                                               //每隔120分钟执行一次
                Trigger   triggertShowGoods = new SimpleTrigger("QuartzShowGoodsJob", "group1", "job1", "group1", tsShowGoods, null,
                                                                SimpleTrigger.RepeatIndefinitely, intervaShowGoods); //每若干小时运行一次,小时间隔由appsettings中的IndexIntervalHour参数指定

                sched.AddJob(jobShowGoods, true);
                sched.ScheduleJob(triggertShowGoods);
                sched.Start();
            }
            catch (Exception ex)
            {
                LogHelper.Error("QuartzManaer异常", ex);
            }
        }
示例#17
0
        /// <summary>
        /// Don't use this method. It is used by QueuedJob's Execute().
        /// </summary>
        public void ScheduleNext()
        {
            lock (queueLock)
            {
                if (queue.Count > 0)
                {
                    QueuedJobDetail queuedJobDetail = queue.Dequeue();

                    JobDetail jobDetail = new JobDetail("QueueJob" + counter, null, queuedJobDetail.JobType);
                    jobDetail.Volatile = true;

                    jobDetail.JobDataMap             = queuedJobDetail.JobDataMap;
                    jobDetail.JobDataMap["JobQueue"] = this;

                    Trigger trigger = new SimpleTrigger("QueueJobTrigger" + counter, null, queuedJobDetail.StartTime);

                    scheduler.ScheduleJob(jobDetail, trigger);

                    counter++;

                    scheduled = true;

                    return;
                }

                scheduled = false;
            }
        }
示例#18
0
        public void ShouldScheduleJobWithSimpleTriggerWhenCalledScheduleTrigger()
        {
            // Arrange
            var myTrigger = new SimpleTrigger
            {
                Name           = "TestTrigger",
                Group          = "TestGroup",
                JobName        = "TestJobName",
                JobGroup       = "TestJobGroup",
                RepeatCount    = 2,
                RepeatInterval = new TimeSpan(0, 0, 0, 1)
            };
            IJobDetail noOpJob = new JobDetailImpl("TestJobName", "TestJobGroup", typeof(NoOpJob));

            _mockScheduler.Setup(x => x.GetJobDetail(It.IsAny <JobKey>())).Returns(noOpJob);
            _mockScheduler.Setup(x => x.CheckExists(It.IsAny <JobKey>())).Returns(true);

            ISchedulerCore schedulerCore = new SchedulerCore(_mockScheduler.Object, _mockPersistanceStore.Object);

            // Act
            schedulerCore.ScheduleTrigger(myTrigger);

            // Assert
            _mockScheduler.Verify(x => x.ScheduleJob(
                                      It.Is <ISimpleTrigger>(t => t.RepeatCount == 2)), Times.Once);
        }
示例#19
0
        public static TriggerFiredBundle NewMinimalTriggerFiredBundle()
        {
            JobDetail          jd       = new JobDetail("jobName", "jobGroup", typeof(NoOpJob));
            SimpleTrigger      trigger  = new SimpleTrigger("triggerName", "triggerGroup");
            TriggerFiredBundle retValue = new TriggerFiredBundle(jd, trigger, null, false, null, null, null, null);

            return(retValue);
        }
        /// <summary>
        /// 按每天
        /// </summary>
        /// <returns></returns>
        private Trigger GetTriggerEveryDay()
        {
            //TODO:检验规则是否合法

            Trigger trigger = new CronTrigger();

            double dblStartNDay = Convert.ToDouble(nDay.Value);

            if (cbEndDatetime.Checked)
            {
                if (rbtEveryDay.Checked)
                {
                    string cronExpression = string.Format("{0} {1} {2} ? * *", GetTrigSecond(), GetTrigMinute(), GetTrigHour());
                    trigger = new CronTrigger(txtTriggerName.Text, txtTriggerGroup.Text, JobName, JobGroupName, GetStartDateTime(), GetEndDateTime(), cronExpression);
                }
                if (rbtEveryWeekDay.Checked)
                {
                    string cronExpression = string.Format("{0} {1} {2} ? * {3}", GetTrigSecond(), GetTrigMinute(), GetTrigHour(), "MON-FRI");
                    trigger = new CronTrigger(txtTriggerName.Text, txtTriggerGroup.Text, JobName, JobGroupName, GetStartDateTime(), GetEndDateTime(), cronExpression);
                }
                if (rbtEveryWeekend.Checked)
                {
                    string cronExpression = string.Format("{0} {1} {2} ? * {3}", GetTrigSecond(), GetTrigMinute(), GetTrigHour(), "SAT-SUN");
                    trigger = new CronTrigger(txtTriggerName.Text, txtTriggerGroup.Text, JobName, JobGroupName, GetStartDateTime(), GetEndDateTime(), cronExpression);
                }
                if (rbtEveryNDay.Checked)
                {
                    //string cronExpression = string.Format("{0} {1} {2} {3} * ?", GetTrigHour(), GetTrigMinute(), GetTrigSecond(), strStartNDay);
                    //trigger = new CronTrigger(txtTriggerName.Text, txtTriggerGroup.Text, JobName, JobGroupName, GetStartDateTime(), GetEndDateTime(), cronExpression);
                    //SimpleTrigger
                    trigger = new SimpleTrigger(txtTriggerName.Text, txtTriggerGroup.Text, JobName, JobGroupName, GetStartDateTime(), GetEndDateTime(), 0, TimeSpan.FromDays(dblStartNDay));
                }
                return(trigger);
            }
            else
            {
                if (rbtEveryDay.Checked)
                {
                    string cronExpression = string.Format("{0} {1} {2} ? * *", GetTrigSecond(), GetTrigMinute(), GetTrigHour());
                    trigger = new CronTrigger(txtTriggerName.Text, txtTriggerGroup.Text, JobName, JobGroupName, GetStartDateTime(), null, cronExpression);
                }
                if (rbtEveryWeekDay.Checked)
                {
                    string cronExpression = string.Format("{0} {1} {2} ? * {3}", GetTrigSecond(), GetTrigMinute(), GetTrigHour(), "MON-FRI");
                    trigger = new CronTrigger(txtTriggerName.Text, txtTriggerGroup.Text, JobName, JobGroupName, GetStartDateTime(), null, cronExpression);
                }
                if (rbtEveryWeekend.Checked)
                {
                    string cronExpression = string.Format("{0} {1} {2} ? * {3}", GetTrigSecond(), GetTrigMinute(), GetTrigHour(), "SAT-SUN");
                    trigger = new CronTrigger(txtTriggerName.Text, txtTriggerGroup.Text, JobName, JobGroupName, GetStartDateTime(), null, cronExpression);
                }
                if (rbtEveryNDay.Checked)
                {
                    trigger = new SimpleTrigger(txtTriggerName.Text, txtTriggerGroup.Text, JobName, JobGroupName, GetStartDateTime(), null, 0, TimeSpan.FromDays(dblStartNDay));
                }
                return(trigger);
            }
        }
        public void TestCreateJobInstance_SimpleDefaults()
        {
            Trigger            trigger = new SimpleTrigger();
            TriggerFiredBundle bundle  = TestUtil.CreateMinimalFiredBundleWithTypedJobDetail(typeof(NoOpJob), trigger);

            IJob job = factory.NewJob(bundle);

            Assert.IsNotNull(job, "Created job was null");
        }
示例#22
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(ListenerExample));

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

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

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

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

            // schedule a job to run immediately
            JobDetail     job     = new JobDetail("job1", "group1", typeof(SimpleJob1));
            SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1", DateTime.UtcNow, null, 0, TimeSpan.Zero);

            // Set up the listener
            IJobListener listener = new Job1Listener();

            sched.AddJobListener(listener);

            // make sure the listener is associated with the job
            job.AddJobListener(listener.Name);

            // schedule the job to run
            sched.ScheduleJob(job, trigger);

            // All of the jobs have been added to the scheduler, but none of the jobs
            // will run until the scheduler has been started
            log.Info("------- Starting Scheduler ----------------");
            sched.Start();

            // wait 30 seconds:
            // note:  nothing will run
            log.Info("------- Waiting 30 seconds... --------------");
            try
            {
                // wait 30 seconds to show jobs
                Thread.Sleep(TimeSpan.FromSeconds(30));
                // executing...
            }
            catch (ThreadInterruptedException)
            {
            }


            // shut down the scheduler
            log.Info("------- Shutting Down ---------------------");
            sched.Shutdown(true);
            log.Info("------- Shutdown Complete -----------------");

            SchedulerMetaData metaData = sched.GetMetaData();

            log.Info(string.Format("Executed {0} jobs.", metaData.NumJobsExecuted));
        }
示例#23
0
 public void ScheduleCollection(
     string collectRequestId, string targetAddress, DateTime date)
 {
     if (!this.IsThereJobForCollectRequest(collectRequestId))
     {
         var job     = this.NewJob(collectRequestId, targetAddress);
         var trigger = new SimpleTrigger(collectRequestId, JobInfoFields.GROUP_NAME, date);
         this.Scheduler.ScheduleJob(job, trigger);
     }
 }
示例#24
0
        private void Start()
        {
            controllerDetector = Instantiate(ControllerDetectorPrefab);
            controllerDetector.TriggerEnter += OnControllerEnterArea;
            controllerDetector.TriggerExit  += OnControllerLeaveArea;

            CreateCord();
            state = State.Free;
            StartCoroutine(FSM());
        }
        public void TestSetTriggersAddsTrigger()
        {
            SimpleTrigger st       = new SimpleTrigger("foo", "bar", DateTime.MinValue);
            ArrayList     triggers = new ArrayList();

            triggers.Add(st);
            bundle.Triggers = triggers;
            Assert.AreSame(triggers, bundle.Triggers);
            Assert.AreEqual(1, bundle.Triggers.Count);
        }
示例#26
0
        protected virtual JobExecutionContext CreateJobExecutionContext()
        {
            Trigger t = new SimpleTrigger();

            JobExecutionContext ctx = new JobExecutionContext(
                null,
                TestUtil.CreateMinimalFiredBundleWithTypedJobDetail(typeof(NoOpJob), t),
                null);

            return(ctx);
        }
        private void ScheduleRetryableJob(JobExecutionContext context, IRetryableJob retryableJob)
        {
            var oldTrigger = context.Trigger;

            // Unschedule old trigger
            _scheduler.UnscheduleJob(oldTrigger.Name, oldTrigger.Group);

            // Create and schedule new trigger
            var retryTrigger = new SimpleTrigger(oldTrigger.Name, oldTrigger.Group, retryableJob.StartTimeRetryUtc, retryableJob.EndTimeRetryUtc, 0, TimeSpan.Zero);
            _scheduler.ScheduleJob(context.JobDetail, retryTrigger);
        }
示例#28
0
        protected virtual JobExecutionContext CreateCleanTimeoutJobExecutionContext(int days)
        {
            SimpleTrigger trigger = new SimpleTrigger();

            JobExecutionContext ctx = new JobExecutionContext(
                null,
                CreateFiredBundleWithTypedJobDetail(typeof(CleanDispositions), trigger),
                null);

            ctx.JobDetail.JobDataMap.Put("Days", days);
            return(ctx);
        }
        private void ScheduleRetryableJob(JobExecutionContext context, IRetryableJob retryableJob)
        {
            var oldTrigger = context.Trigger;

            // Unschedule old trigger
            _scheduler.UnscheduleJob(oldTrigger.Name, oldTrigger.Group);

            // Create and schedule new trigger
            var retryTrigger = new SimpleTrigger(oldTrigger.Name, oldTrigger.Group, retryableJob.StartTimeRetryUtc, retryableJob.EndTimeRetryUtc, 0, TimeSpan.Zero);

            _scheduler.ScheduleJob(context.JobDetail, retryTrigger);
        }
示例#30
0
        private void AddErrorCommodityOrderJobNow(IScheduler scheduler, System.Collections.IDictionary param)
        {
            JobDetail job = scheduler.GetJobDetail("ErrorCommodityOrderJobNow", "Jinher.AMP.BTP.Job");

            job = new JobDetail("ErrorCommodityOrderJobNow", "Jinher.AMP.BTP.Job", typeof(ErrorCommodityOrderJob));
            job.JobDataMap.PutAll(param);

            DateTime      now        = DateTime.UtcNow;//发布时运行一次
            SimpleTrigger triggerNow = new SimpleTrigger("ErrorCommodityOrderTriggerNow", "Jinher.AMP.BTP.Job", now);

            triggerNow.Description = "ErrorCommodityOrderJob触发器";
            scheduler.ScheduleJob(job, triggerNow);
        }
示例#31
0
        public void TestTriggerMisfiredMessage()
        {
            // expectations
            Expect.Call(mockLog.IsInfoEnabled).Return(true);
            mockLog.Info(null);
            LastCall.IgnoreArguments();

            mockery.ReplayAll();

            Trigger t = new SimpleTrigger();

            plugin.TriggerMisfired(t);
        }
示例#32
0
        private void CrowdfundingCalcJobNow(IScheduler scheduler, System.Collections.IDictionary param)
        {
            JobDetail job = scheduler.GetJobDetail("CrowdfundingCalcJobNow", "Jinher.AMP.BTP.Job");

            job = new JobDetail("CrowdfundingCalcJobNow", "Jinher.AMP.BTP.Job", typeof(CrowdfundingCalcJob));
            job.JobDataMap.PutAll(param);

            DateTime      now        = DateTime.UtcNow;//发布时运行一次
            SimpleTrigger triggerNow = new SimpleTrigger("CrowdfundingCalcTriggerNow", "Jinher.AMP.BTP.Job", now);

            triggerNow.Description = "CrowdfundingCalcNow触发器";
            scheduler.ScheduleJob(job, triggerNow);
        }
示例#33
0
        public void TestPauseTriggerSetsTriggerIntoPausedStateAndResumeTriggersSetsTriggerBackToNormalState()
        {
            // Arrange
            Scheduler.Shutdown();
            Scheduler.Initialize((config =>
            {
                config.EnableWebApiSelfHost = false;
                config.EnableAuditHistory = false;
            }));
            IPersistanceStore persistanceStore = new InMemoryStore();
            _schedulerCore = new SchedulerCore(Scheduler.Instance(), persistanceStore);

            const string jobName = "Job1";
            const string jobGroup = "Group1";
            const string triggerName = "Trigger1";

            _schedulerCore.CreateJob(jobName, jobGroup, typeof(NoOpJob), new Dictionary<string, object>(), string.Empty);

            var simpleTrigger = new SimpleTrigger
            {
                RepeatCount = 1,
                RepeatInterval = new TimeSpan(0, 1, 0, 0),
                JobName = jobName,
                JobGroup = jobGroup,
                Name = triggerName
            };

            var triggerId = _schedulerCore.ScheduleTrigger(simpleTrigger);


            // Act / Assert
            _schedulerCore.PauseTrigger(triggerId);
            Assert.Equal(TriggerState.Paused, Scheduler.Instance().GetTriggerState(new TriggerKey(triggerName)));

            _schedulerCore.ResumeTrigger(triggerId);
            Assert.Equal(TriggerState.Normal, Scheduler.Instance().GetTriggerState(new TriggerKey(triggerName)));
        }
	    private void ProcessJobs(quartz data)
	    {
            if (data.job == null)
            {
                // no jobs to process, file is empty
                return;
            }

	        foreach (jobType jt in data.job)
	        {
	            JobSchedulingBundle jsb = new JobSchedulingBundle();
	            jobdetailType j = jt.jobdetail;
	            Type jobType = Type.GetType(j.jobtype);
                if (jobType == null)
                {
                    throw new SchedulerConfigException("Unknown job type " + j.jobtype);
                }

	            JobDetail jd = new JobDetail(j.name, j.group, jobType, j.@volatile, j.durable, j.recover);
	            jd.Description = j.description;

                if (j.joblistenerref != null && j.joblistenerref.Trim().Length > 0)
                {
                    jd.AddJobListener(j.joblistenerref);
                }
                
                jsb.JobDetail = jd;

                // read job data map
                if (j.jobdatamap != null && j.jobdatamap.entry != null)
                {
                    foreach (entryType entry in j.jobdatamap.entry)
                    {
                        jd.JobDataMap.Put(entry.key, entry.value);
                    }
                }

	            triggerType[] tArr = jt.trigger;
                if (tArr == null)
                {
                    // set to empty
                    tArr = new triggerType[0];
                }
	            foreach (triggerType t in tArr)
	            {
	                Trigger trigger;
	                if (t.Item is cronType)
	                {
	                    cronType c = (cronType) t.Item;

                        DateTime startTime = (c.starttime == DateTime.MinValue ? DateTime.UtcNow : c.starttime);
                        NullableDateTime endTime = (c.endtime == DateTime.MinValue ? null : (NullableDateTime)c.endtime);

	                    string jobName = c.jobname != null ? c.jobname : j.name;
	                    string jobGroup = c.jobgroup != null ? c.jobgroup : j.group;

                        CronTrigger ct = new CronTrigger(
                            c.name,
                            c.group,
                            jobName,
                            jobGroup,
                            startTime,
                            endTime,
                            c.cronexpression);

	                    if (c.timezone != null && c.timezone.Trim().Length > 0)
	                    {
#if NET_35
                            ct.TimeZone = TimeZoneInfo.FindSystemTimeZoneById(c.timezone);
#else
	                        throw new ArgumentException(
	                            "Specifying time zone for cron trigger is only supported in .NET 3.5 builds");
#endif
	                    }
	                    trigger = ct;
	                }
	                else if (t.Item is simpleType)
	                {
	                    simpleType s = (simpleType) t.Item;
	                    
	                    DateTime startTime = (s.starttime == DateTime.MinValue ? DateTime.UtcNow : s.starttime);
                        NullableDateTime endTime = (s.endtime == DateTime.MinValue ? null : (NullableDateTime)s.endtime);

                        string jobName = s.jobname != null ? s.jobname : j.name;
                        string jobGroup = s.jobgroup != null ? s.jobgroup : j.group;

                        SimpleTrigger st = new SimpleTrigger(
                            s.name, 
                            s.group, 
                            jobName, 
                            jobGroup,
                            startTime, 
                            endTime, 
                            ParseSimpleTriggerRepeatCount(s.repeatcount), 
                            TimeSpan.FromMilliseconds(Convert.ToInt64(s.repeatinterval, CultureInfo.InvariantCulture)));

	                    trigger = st;
	                }
	                else
	                {
	                    throw new ArgumentException("Unknown trigger type in XML");
	                }

                    trigger.Description = t.Item.description;
	                trigger.CalendarName = t.Item.calendarname;
                    
                    if (t.Item.misfireinstruction != null)
                    {
                        trigger.MisfireInstruction = ReadMisfireInstructionFromString(t.Item.misfireinstruction);
                    }
                    if (t.Item.jobdatamap != null && t.Item.jobdatamap.entry != null)
                    {
                        foreach (entryType entry in t.Item.jobdatamap.entry)
                        {
                            if (trigger.JobDataMap.Contains(entry.key))
                            {
                                Log.Warn("Overriding key '" + entry.key + "' with another value in same trigger job data map");
                            }
                            trigger.JobDataMap[entry.key] = entry.value;
                        }
                    }
					if (t.Item.triggerlistenerref != null && t.Item.triggerlistenerref.Trim().Length > 0)
					{
						trigger.AddTriggerListener(t.Item.triggerlistenerref);
					}
					
	                jsb.Triggers.Add(trigger);
	            }

	            AddJobToSchedule(jsb);
	        }
	    }
示例#35
0
        /// <summary>
        /// Called when the associated <see cref="IScheduler"/> is started, in order
        /// to let the plug-in know it can now make calls into the scheduler if it
        /// needs to.
        /// </summary>
        public virtual void Start()
        {
            try
            {
                if (jobFiles.Count > 0)
                {
                    if (scanInterval > TimeSpan.Zero)
                    {
                        scheduler.Context.Put(JobInitializationPluginName + '_' + Name, this);
                    }

                    foreach (JobFile jobFile in jobFiles.Values)
                    {

                        if (scanInterval > TimeSpan.Zero)
                        {
                            String jobTriggerName = BuildJobTriggerName(jobFile.FileBasename);

                            SimpleTrigger trig = new SimpleTrigger(
                                jobTriggerName,
                                JobInitializationPluginName,
                                DateTime.UtcNow, null,
                                SimpleTrigger.RepeatIndefinitely, scanInterval);
                            trig.Volatile = true;

                            JobDetail job = new JobDetail(
                                jobTriggerName,
                                JobInitializationPluginName,
                                typeof(FileScanJob));

                            job.Volatile = true;
                            job.JobDataMap.Put(FileScanJob.FileName, jobFile.FilePath);
                            job.JobDataMap.Put(FileScanJob.FileScanListenerName, JobInitializationPluginName + '_' + Name);

                            scheduler.ScheduleJob(job, trig);
                        }

                        ProcessFile(jobFile);
                    }
                }
            }
            catch (SchedulerException se)
            {
                Log.Error("Error starting background-task for watching jobs file.", se);
            }
            finally
            {
                started = true;
            }
        }
示例#36
0
        public void ShouldScheduleJobWithSimpleTriggerWhenCalledScheduleTrigger()
        {
            // Arrange
            var myTrigger = new SimpleTrigger
            {
                Name = "TestTrigger",
                Group = "TestGroup",
                JobName = "TestJobName",
                JobGroup = "TestJobGroup",
                RepeatCount = 2,
                RepeatInterval = new TimeSpan(0,0,0,1)
            };
            IJobDetail noOpJob = new JobDetailImpl("TestJobName", "TestJobGroup", typeof(NoOpJob));
            _mockScheduler.Setup(x => x.GetJobDetail(It.IsAny<JobKey>())).Returns(noOpJob);
            _mockScheduler.Setup(x => x.CheckExists(It.IsAny<JobKey>())).Returns(true);

            ISchedulerCore schedulerCore = new SchedulerCore(_mockScheduler.Object, _mockPersistanceStore.Object);
            
            // Act 
            schedulerCore.ScheduleTrigger(myTrigger);

            // Assert
            _mockScheduler.Verify(x => x.ScheduleJob(
                It.Is<ISimpleTrigger>(t => t.RepeatCount == 2)), Times.Once);
        }