예제 #1
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 -----------------");
        }
예제 #2
0
파일: Program.cs 프로젝트: Angliy/DevFx
        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
        /// <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;
            }
        }
        public void LoadDataJob(string model, string path, dynamic user)
        {
            string typeName = "MVC_Husk.Infrastructure.BackgroundJobs.Load" + model + "Job";
            Type modelType = Type.GetType(typeName);

            if (modelType != null)
            {
                string description = "Load File for " + model + " at " + path;
                JobDetail details = new JobDetail(description, modelType);
                details.JobDataMap["path"] = path;
                details.Description = "Job that loads Seasonal Products data uploaded via the application into the database";
                details.Group = "Data Load";

                Trigger trigger = new SimpleTrigger("QuartzManager LoadDataJob", DateTime.Now);
                trigger.Description = "Trigger immediately";
                trigger.Group = "Immediate";

                dynamic result = _jobs.CreateJob(description, 1, DateTime.Now, user.ID);
                details.JobDataMap["QueueID"] = result.JobId;
                _scheduler.ScheduleJob(details, trigger);
            }
            else
            {
                _logger.LogError("There is no " + typeName + "defined");
                throw new NullReferenceException("There is no " + typeName + "defined");
            }
        }
        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");
        }
예제 #6
0
        /// <summary>
        /// Make a trigger that will fire <param name="repeatCount" /> times, waiting
        /// <param name="repeatInterval" /> between each fire.
        /// </summary>
        /// <remarks>
        /// The generated trigger will not have its name, group,
        /// or end-time set.  The Start time defaults to 'now'.
        /// </remarks>
        /// <returns>the newly created trigger</returns>
        public static Trigger MakeImmediateTrigger(int repeatCount, TimeSpan repeatInterval)
        {
            SimpleTrigger trig = new SimpleTrigger();

            trig.StartTimeUtc   = DateTime.UtcNow;
            trig.RepeatCount    = repeatCount;
            trig.RepeatInterval = repeatInterval;
            return(trig);
        }
예제 #7
0
        /// <summary>
        /// Make a trigger that will fire every N hours, with the given number of
        /// repeats.
        /// <p>
        /// The generated trigger will not have its name, group,
        /// or end-time set.  The Start time defaults to 'now'.
        /// </p>
        /// </summary>
        /// <param name="intervalInHours">the number of hours between firings</param>
        /// <param name="repeatCount">the number of times to repeat the firing</param>
        /// <returns>the new trigger</returns>
        public static Trigger MakeHourlyTrigger(int intervalInHours, int repeatCount)
        {
            SimpleTrigger trig = new SimpleTrigger();

            trig.RepeatInterval = TimeSpan.FromHours(intervalInHours);
            trig.RepeatCount    = repeatCount;
            trig.StartTimeUtc   = DateTime.UtcNow;

            return(trig);
        }
예제 #8
0
        /// <summary>
        /// Make a trigger that will fire every N minutes, with the given number of
        /// repeats.
        /// <p>
        /// The generated trigger will not have its name, group,
        /// or end-time set.  The Start time defaults to 'now'.
        /// </p>
        /// </summary>
        /// <param name="intervalInMinutes">the number of minutes between firings</param>
        /// <param name="repeatCount">the number of times to repeat the firing</param>
        /// <returns>the new trigger</returns>
        public static Trigger MakeMinutelyTrigger(int intervalInMinutes, int repeatCount)
        {
            var trig = new SimpleTrigger();

            trig.RepeatInterval = TimeSpan.FromMinutes(intervalInMinutes);
            trig.RepeatCount    = repeatCount;
            trig.StartTimeUtc   = DateTime.UtcNow;

            return(trig);
        }
예제 #9
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);
     }
 }
예제 #10
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;
        }
예제 #11
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting scheduler...");

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

            // set thread pool infoD:\Projects\QuartzMaster\QuartzMaster.TestServerHost\Program.cs
            properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"] = "5";
            properties["quartz.threadPool.threadPriority"] = "Normal";

            // set remoting expoter
            properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
            properties["quartz.scheduler.exporter.port"] = "500";
            properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
            properties["quartz.scheduler.exporter.channelType"] = "tcp";

            var schedulerFactory = new StdSchedulerFactory(properties);
            scheduler = schedulerFactory.GetScheduler();

            // define the job and ask it to run
            var map = new JobDataMap();
            map.Put("msg", "Some message!");
            map.Put("msg 2", "Some message 2!");
            map.Put("msg 3", "Some message 3!");

            var job = new JobDetail("localJob", "default", typeof(NoOpJob))
            {
                JobDataMap = map
            };

            var job2 = new JobDetail("localJob 2", "default", typeof(NoOpJob))
            {
                JobDataMap = map
            };

            var trigger2 = new SimpleTrigger("Simple Trigger", "default", "localJob 2", "default", DateTime.Now, DateTime.Now.AddMinutes(10), SimpleTrigger.RepeatIndefinitely, new TimeSpan(0, 0, 45));

            var trigger = new CronTrigger("remotelyAddedTrigger", "default", "localJob", "default", DateTime.UtcNow, null, "/5 * * ? * *");

            var trigger3 = new SimpleTrigger("remotelyAddedTriggerB", "default", "localJob", "default", DateTime.Now, DateTime.Now.AddMinutes(10), SimpleTrigger.RepeatIndefinitely, new TimeSpan(0, 0, 45));

            // schedule the job
            scheduler.ScheduleJob(job, trigger3);
            scheduler.ScheduleJob(job2, trigger2);

            scheduler.Start();

            Console.WriteLine("Scheduler has been started.");
            Console.WriteLine("Press any key to stop scheduler");
            Console.ReadKey();
            scheduler.Shutdown();
        }
		public override void Execute(Job job)
		{
			Instances.MainCounterStore.Increment(new Caching.CacheKey(Caching.CacheKeyPrefix.JobQueued, Timeslots.GetCurrentTimeslot().StartTime.ToString()), () => 0);
			JobDetail jobDetail = new JobDetail(job.Name, "immediate", job.GetType());
			jobDetail.JobDataMap = job.JobDataMap;
			SimpleTrigger trigger = new SimpleTrigger("Trigger" + job.Name, "immediate");
			ISchedulerFactory schedulerFactory = new StdSchedulerFactory(Common.Properties.QuartzSchedulerProperties);
			IScheduler scheduler = schedulerFactory.GetScheduler();
			scheduler.ScheduleJob(jobDetail, trigger);
			
		}
        public void Schedule(DateTime date, Action action)
        {
            JobDetail jobDetail = new JobDetail(Guid.NewGuid().ToString(), null, typeof(DateJob));
            jobDetail.JobDataMap["Listener"] = action;
            SimpleTrigger trigger = new SimpleTrigger(Guid.NewGuid().ToString(),
                                          null,
                                          date,
                                          null,
                                          0,
                                          TimeSpan.Zero);

            sched.ScheduleJob(jobDetail, trigger);
        }
예제 #14
0
        public void TestCreateJobInstance_IgnoredProperties()
        {
            factory.IgnoredUnknownProperties = new string[] {"foo", "baz"};
            Trigger trigger = new SimpleTrigger();
            trigger.JobDataMap["foo"] = "should not be injected";
            trigger.JobDataMap["number"] = 123;
            TriggerFiredBundle bundle = TestUtil.CreateMinimalFiredBundleWithTypedJobDetail(typeof(InjectableJob), trigger);

            InjectableJob job = (InjectableJob)factory.NewJob(bundle);
            Assert.IsNotNull(job, "Created job was null");
            Assert.AreEqual(123, job.Number, "integer injection failed");
            Assert.IsNull(job.Foo, "foo was injected when it was not supposed to    ");
        }
예제 #15
0
        public void TestForQuartzTrigger()
        {
            IScheduler scheduler = binder.GetInstance<IScheduler>();

            JobDetail jobDetail = new JobDetail("TestQuartz", typeof(TestJob));
            DateTime dateTime = DateTime.UtcNow.AddSeconds(1);
            Trigger trigger = new SimpleTrigger("TestQuartzTrigger", dateTime);
            scheduler.ScheduleJob(jobDetail, trigger);

            Thread.Sleep(3000);

            Assert.IsTrue(Triggered);
        }
예제 #16
0
        public void TestCreateJobInstance_SchedulerContextGiven()
        {
            IDictionary items = new Hashtable();
            items["foo"] = "bar";
            items["number"] = 123;
            factory.SchedulerContext = new SchedulerContext(items);
            Trigger trigger = new SimpleTrigger();
            TriggerFiredBundle bundle = TestUtil.CreateMinimalFiredBundleWithTypedJobDetail(typeof(InjectableJob), trigger);

            InjectableJob job = (InjectableJob) factory.NewJob(bundle);
            Assert.IsNotNull(job, "Created job was null");
            Assert.AreEqual("bar", job.Foo, "string injection failed");
            Assert.AreEqual(123, job.Number, "integer injection failed");
        }
예제 #17
0
 public static void Start()
 {
     //每隔一段时间执行任务
     IScheduler sched;
     ISchedulerFactory sf = new StdSchedulerFactory();
     sched = sf.GetScheduler();
     JobDetail job = new JobDetail("job1", "group1", typeof(IndexJob));//IndexJob为实现了IJob接口的类
     DateTime ts = TriggerUtils.GetNextGivenSecondDate(null, 5);//5秒后开始第一次运行
     TimeSpan interval = TimeSpan.FromHours(1);//每隔10秒执行一次
     Trigger trigger = new SimpleTrigger("trigger1", "group1", "job1", "group1", ts, null, SimpleTrigger.RepeatIndefinitely, interval);//每若干小时运行一次,小时间隔由appsettings中的IndexIntervalHour参数指定
     sched.AddJob(job, true);
     sched.ScheduleJob(trigger);
     sched.Start();
     //要关闭任务定时则需要sched.Shutdown(true)
 }
예제 #18
0
        public void LongRunningJob(dynamic user)
        {
            string description = "Long Running Task";
            JobDetail details = new JobDetail(description, typeof(LongRunningNotepadJob));
            details.Description = "Long running job";
            details.Group = "External executable job";

            Trigger trigger = new SimpleTrigger("QuartzManager Long Running Task", DateTime.Now);
            trigger.Description = "Trigger immediately";
            trigger.Group = "Immediate";

            dynamic result = _jobs.CreateJob(description, 1, DateTime.Now, user.ID, "LongRunning", 1);
            details.JobDataMap["QueueID"] = result.JobId;
            _scheduler.ScheduleJob(details, trigger);
        }
예제 #19
0
 public void TriggerComplete(Trigger trigger, JobExecutionContext context, SchedulerInstruction triggerInstructionCode)
 {
     if (!trigger.Name.Equals("TimerTrigger"))
     {
         Account account = (Account)trigger.JobDataMap.Get("account");
         if (account != null)
         {
             SimpleTrigger triggerObject = new SimpleTrigger(account.Login + "Trigger", "account", DateTime.MinValue, null, 0, TimeSpan.Zero);
             triggerObject.JobName = account.Login + "Job";
             triggerObject.StartTimeUtc = DateTime.UtcNow.AddSeconds(new Random().Next(account.Settings.NextTimeLoginMin, account.Settings.NextTimeLoginMax));
             account.SchedulerTrigger = triggerObject;
             triggerObject.JobDataMap.Add("account", account);
             m_accountManager.SetNextLoginTimeForAccount(account);
         }
     }
 }
		public override void ExecuteStoredJobs()
		{
			ISchedulerFactory schedulerFactory = new StdSchedulerFactory(Common.Properties.QuartzSchedulerProperties);
			IScheduler scheduler = schedulerFactory.GetScheduler();
			foreach (string jobName in JobNames)
			{
				
				SimpleTrigger trigger = new SimpleTrigger("Trigger" + jobName, "immediate");
				trigger.JobName = jobName;
				trigger.JobGroup = "sequential";
				
				scheduler.ScheduleJob(trigger);
				JobDetail jobDetail = scheduler.GetJobDetail(jobName, "sequential");
				jobDetail.Durable = false;
				scheduler.AddJob(jobDetail, true);
			}
		}
예제 #21
0
        public JobScheduler ScheduleAt(DateTime startDateTime, TimeSpan timeSpan)
        {
            // define the job and ask it to run
            var job = new JobDetail(_name, _jobScheduler.GroupName, typeof (JobBase))
                      	{
                      		JobDataMap = new JobDataMap(
                      			new Dictionary<string, object> {{"action", _action}})
                      	};

            var trigger = new SimpleTrigger("TriggerFor_" + _name, _jobScheduler.GroupName,
                                            _name, _jobScheduler.GroupName,
                                            DateTime.UtcNow, null,
                                            SimpleTrigger.RepeatIndefinitely, timeSpan);

            // schedule the job
            _jobScheduler.Scheduler.ScheduleJob(job, trigger);
            return _jobScheduler;
        }
        public void Should_execute_in_selected_day()
        {
            ISchedulerFactory schedFact = new StdSchedulerFactory();
            IScheduler sched = schedFact.GetScheduler();
            sched.Start();

            JobDetail jobDetail = new JobDetail("myJob", null, typeof(HelloJob));
            SimpleTrigger trigger = new SimpleTrigger("myTrigger",
                                          null,
                                          DateTime.Now.ToUniversalTime(),
                                          null,
                                          0,
                                          TimeSpan.Zero);

            //trigger.StartTimeUtc = TriggerUtils.GetEvenHourDate(DateTime.UtcNow);
            trigger.Name = "myTrigger";
            sched.ScheduleJob(jobDetail, trigger);

            Thread.Sleep(100000);
        }
예제 #23
0
        private void NacasujRozesilani()
        {
            var schedulerFactory = new StdSchedulerFactory();
            _casovac = schedulerFactory.GetScheduler();

            var job = new JobDetail("rozesilani", null, typeof(Rozesilani));
            // Instantiate a trigger using the basic cron syntax.
            var trigger = new SimpleTrigger("spust-rozesilani",
                                            null,
                                            TriggerUtils.MakeWeeklyTrigger(DayOfWeek.Monday,7,0).ComputeFirstFireTimeUtc(null).Value,
                                            null,
                                            SimpleTrigger.RepeatIndefinitely,
                                            TimeSpan.FromDays(7)
                );
            trigger.JobName = job.Name;
            job.JobDataMap["sluzba"] = _sluzba;
            // Add the job to the scheduler
            _casovac.AddJob(job, true);
            _casovac.ScheduleJob(trigger);
        }
예제 #24
0
        public void Execute(JobExecutionContext context)
        {
            try
            {
                // Get sunrise time, sunset time and weather condition
                XElement root = XElement.Load(SharpMonitor.Properties.Settings.Default.WeatherServiceUrl);
                XNamespace yweather = "http://xml.weather.yahoo.com/ns/rss/1.0";

                XElement astronomy = root.Descendants(yweather + "astronomy").First();
                string sunrise = astronomy.Attribute("sunrise").Value;
                string sunset = astronomy.Attribute("sunset").Value;

                DateTime ts = DateTime.ParseExact(
                    String.Format("{0:d/M/yyyy} {1}", DateTime.Today, sunrise),
                    "d/M/yyyy h:mm tt", null);
                DateTime te = DateTime.ParseExact(
                    String.Format("{0:d/M/yyyy} {1}", DateTime.Today, sunset),
                    "d/M/yyyy h:mm tt", null);

                if (DateTime.Now < te)
                {
                    int period = SharpMonitor.Properties.Settings.Default.RepeatIntervalInSeconds;

                    Trigger trigger = new SimpleTrigger("SimpleTrigger",
                        DateTime.Now > ts ? TriggerUtils.GetNextGivenSecondDate(null, period % 60) : ts.ToUniversalTime(),
                        te.ToUniversalTime(),
                        SimpleTrigger.RepeatIndefinitely,
                        TimeSpan.FromSeconds(period));

                    Type jobType = typeof(LogTask);
                    JobDetail job = new JobDetail(jobType.Name, null, jobType);
                    context.Scheduler.ScheduleJob(job, trigger);
                }
            }
            catch (Exception ex)
            {
                throw new JobExecutionException(ex);
            }
        }
 public static Trigger CreateTigger(NodeTaskRuntimeInfo taskruntimeinfo)
 {
     if (taskruntimeinfo.TaskModel.taskcron.Contains("["))
     {
         var customcorn = CustomCornFactory.GetCustomCorn(taskruntimeinfo.TaskModel.taskcron);
         customcorn.Parse();
         if (customcorn is SimpleCorn || customcorn is RunOnceCorn)
         {
             var simplecorn = customcorn as SimpleCorn;
             // 定义调度触发规则,比如每1秒运行一次,共运行8次
             SimpleTrigger simpleTrigger = new SimpleTrigger(taskruntimeinfo.TaskModel.id.ToString(), taskruntimeinfo.TaskModel.categoryid.ToString());
             if (simplecorn.ConInfo.StartTime != null)
                 simpleTrigger.StartTimeUtc = simplecorn.ConInfo.StartTime.Value.ToUniversalTime();
             //else
             //    simpleTrigger.StartTimeUtc = DateTime.Now.ToUniversalTime();
             if (simplecorn.ConInfo.EndTime != null)
                 simpleTrigger.EndTimeUtc = simplecorn.ConInfo.EndTime.Value.ToUniversalTime();
             if (simplecorn.ConInfo.RepeatInterval != null)
                 simpleTrigger.RepeatInterval = TimeSpan.FromSeconds(simplecorn.ConInfo.RepeatInterval.Value);
             else
                 simpleTrigger.RepeatInterval = TimeSpan.FromSeconds(1);
             if (simplecorn.ConInfo.RepeatCount != null)
                 simpleTrigger.RepeatCount = simplecorn.ConInfo.RepeatCount.Value - 1;//因为任务默认执行一次,所以减一次
             else
                 simpleTrigger.RepeatCount = int.MaxValue;//不填,则默认最大执行次数
             return simpleTrigger;
         }
         return null;
     }
     else
     {
         CronTrigger trigger = new CronTrigger(taskruntimeinfo.TaskModel.id.ToString(), taskruntimeinfo.TaskModel.categoryid.ToString());// 触发器名,触发器组  
         trigger.CronExpressionString = taskruntimeinfo.TaskModel.taskcron;// 触发器时间设定  
         return trigger;
     }
 }
예제 #26
0
        /// <summary>
        /// Schedules the integration services job.
        /// </summary>
        /// <param name="job">The job that schedules integration service calls.</param>
        /// <param name="interval">The interval.</param>
        private static void ScheduleIntegrationServicesJob(JobDetail job, TimeSpan interval)
        {
            var trigger = Scheduler.GetTriggersOfJob(job.Name, job.Group).OfType<SimpleTrigger>().FirstOrDefault();

            if (trigger != null && trigger.RepeatInterval != interval)
            {
                Scheduler.UnscheduleJob(trigger.Name, trigger.Group);
                trigger = null;
            }

            if (trigger != null)
                return;

            trigger = new SimpleTrigger(
                IntegrationServicesTriggerName,
                IntegrationServicesGroupName,
                job.Name,
                job.Group,
                DateTime.UtcNow,
                null,
                SimpleTrigger.RepeatIndefinitely,
                interval);
            Scheduler.ScheduleJob(trigger);
        }
예제 #27
0
        public void TestAfterPropertiesSet_Trigger_TriggerDoesntExist()
        {
            mockery = new MockRepository();
            InitForAfterPropertiesSetTest();

            const string TRIGGER_NAME = "trigName";
            const string TRIGGER_GROUP = "trigGroup";
            SimpleTrigger trigger = new SimpleTrigger(TRIGGER_NAME, TRIGGER_GROUP);
            factory.Triggers = new Trigger[] { trigger };

            Expect.Call(TestSchedulerFactory.MockScheduler.GetTrigger(TRIGGER_NAME, TRIGGER_GROUP)).Return(null);
            TestSchedulerFactory.MockScheduler.ScheduleJob(trigger);
            LastCall.IgnoreArguments().Return(DateTime.UtcNow);
                

            TestSchedulerFactory.Mockery.ReplayAll();
            mockery.ReplayAll();
            factory.AfterPropertiesSet();

        }
예제 #28
0
        public void TestAfterPropertiesSet_Trigger_TriggerExists()
        {
            mockery = new MockRepository();
            InitForAfterPropertiesSetTest();

            const string TRIGGER_NAME = "trigName";
            const string TRIGGER_GROUP = "trigGroup";
            SimpleTrigger trigger = new SimpleTrigger(TRIGGER_NAME, TRIGGER_GROUP);
            factory.Triggers = new Trigger[] { trigger };

            Expect.Call(TestSchedulerFactory.MockScheduler.GetTrigger(TRIGGER_NAME, TRIGGER_GROUP)).Return(trigger);

            TestSchedulerFactory.Mockery.ReplayAll();
            mockery.ReplayAll();
            factory.AfterPropertiesSet();
        }
		/// <summary>
		/// Make a trigger that will fire every N hours, with the given number of
		/// repeats.
		/// <p>
		/// The generated trigger will not have its name, group,
		/// or end-time set.  The Start time defaults to 'now'.
		/// </p>
		/// </summary>
		/// <param name="intervalInHours">the number of hours between firings</param>
		/// <param name="repeatCount">the number of times to repeat the firing</param>
		/// <returns>the new trigger</returns>
		public static Trigger MakeHourlyTrigger(int intervalInHours, int repeatCount)
		{
			SimpleTrigger trig = new SimpleTrigger();

			trig.RepeatInterval = TimeSpan.FromHours(intervalInHours);
			trig.RepeatCount = repeatCount;
			trig.StartTimeUtc = DateTime.UtcNow;

			return trig;
		}
		/// <summary>
		/// Make a trigger that will fire <param name="repeatCount" /> times, waiting
		/// <param name="repeatInterval" /> between each fire.
		/// </summary>
		/// <remarks>
		/// The generated trigger will not have its name, group,
		/// or end-time set.  The Start time defaults to 'now'.
        /// </remarks>
		/// <returns>the newly created trigger</returns>
		public static Trigger MakeImmediateTrigger(int repeatCount, TimeSpan repeatInterval)
		{
			SimpleTrigger trig = new SimpleTrigger();
			trig.StartTimeUtc = DateTime.UtcNow;
			trig.RepeatCount = repeatCount;
			trig.RepeatInterval = repeatInterval;
			return trig;
		}
        /// <summary>
        /// Trigger the identified <see cref="IJob" /> (Execute it
        /// now) - with a volatile trigger.
        /// </summary>
        public virtual void TriggerJobWithVolatileTrigger(SchedulingContext ctxt, string jobName, string groupName,
                                                          JobDataMap data)
        {
            ValidateState();

            if (groupName == null)
            {
                groupName = SchedulerConstants.DefaultGroup;
            }

            Trigger trig =
                new SimpleTrigger(NewTriggerId(), SchedulerConstants.DefaultManualTriggers, jobName, groupName, DateTime.UtcNow,
                                  null, 0, TimeSpan.Zero);
            trig.Volatile = true;
            trig.ComputeFirstFireTimeUtc(null);
            if (data != null)
            {
                trig.JobDataMap = data;
            }

            bool collision = true;
            while (collision)
            {
                try
                {
                    resources.JobStore.StoreTrigger(ctxt, trig, false);
                    collision = false;
                }
                catch (ObjectAlreadyExistsException)
                {
                    trig.Name = NewTriggerId();
                }
            }

            NotifySchedulerThread(trig.GetNextFireTimeUtc());
            NotifySchedulerListenersScheduled(trig);
        }
        protected virtual void ClusterRecover(ConnectionAndTransactionHolder conn, IList failedInstances)
        {
            if (failedInstances.Count > 0)
            {
                long recoverIds = DateTime.UtcNow.Ticks;

                LogWarnIfNonZero(failedInstances.Count,
                                 "ClusterManager: detected " + failedInstances.Count + " failed or restarted instances.");
                try
                {
                    foreach (SchedulerStateRecord rec in failedInstances)
                    {
                        Log.Info("ClusterManager: Scanning for instance \"" + rec.SchedulerInstanceId +
                                 "\"'s failed in-progress jobs.");

                        IList firedTriggerRecs =
                            Delegate.SelectInstancesFiredTriggerRecords(conn, rec.SchedulerInstanceId);

                        int acquiredCount = 0;
                        int recoveredCount = 0;
                        int otherCount = 0;

                        ISet triggerKeys = new HashSet();

                        foreach (FiredTriggerRecord ftRec in firedTriggerRecs)
                        {
                            Key tKey = ftRec.TriggerKey;
                            Key jKey = ftRec.JobKey;

                            triggerKeys.Add(tKey);

                            // release blocked triggers..
                            if (ftRec.FireInstanceState.Equals(StateBlocked))
                            {
                                Delegate.UpdateTriggerStatesForJobFromOtherState(conn, jKey.Name, jKey.Group,
                                                                                 StateWaiting,
                                                                                 StateBlocked);
                            }
                            else if (ftRec.FireInstanceState.Equals(StatePausedBlocked))
                            {
                                Delegate.UpdateTriggerStatesForJobFromOtherState(conn, jKey.Name, jKey.Group,
                                                                                 StatePaused,
                                                                                 StatePausedBlocked);
                            }

                            // release acquired triggers..
                            if (ftRec.FireInstanceState.Equals(StateAcquired))
                            {
                                Delegate.UpdateTriggerStateFromOtherState(conn, tKey.Name, tKey.Group, StateWaiting,
                                                                          StateAcquired);
                                acquiredCount++;
                            }
                            else if (ftRec.JobRequestsRecovery)
                            {
                                // handle jobs marked for recovery that were not fully
                                // executed..
                                if (JobExists(conn, jKey.Name, jKey.Group))
                                {
                                    DateTime tempAux = new DateTime(ftRec.FireTimestamp);
                                    SimpleTrigger rcvryTrig =
                                        new SimpleTrigger(
                                            "recover_" + rec.SchedulerInstanceId + "_" + Convert.ToString(recoverIds++, CultureInfo.InvariantCulture),
                                            SchedulerConstants.DefaultRecoveryGroup, tempAux);
                                    rcvryTrig.Volatile = ftRec.TriggerIsVolatile;
                                    rcvryTrig.JobName = jKey.Name;
                                    rcvryTrig.JobGroup = jKey.Group;
                                    rcvryTrig.MisfireInstruction = MisfireInstruction.SimpleTrigger.FireNow;
                                    rcvryTrig.Priority = ftRec.Priority;
                                    JobDataMap jd = Delegate.SelectTriggerJobDataMap(conn, tKey.Name, tKey.Group);
                                    jd.Put(SchedulerConstants.FailedJobOriginalTriggerName, tKey.Name);
                                    jd.Put(SchedulerConstants.FailedJobOriginalTriggerGroup, tKey.Group);
                                    jd.Put(SchedulerConstants.FailedJobOriginalTriggerFiretimeInMillisecoonds, Convert.ToString(ftRec.FireTimestamp, CultureInfo.InvariantCulture));
                                    rcvryTrig.JobDataMap = jd;

                                    rcvryTrig.ComputeFirstFireTimeUtc(null);
                                    StoreTrigger(conn, null, rcvryTrig, null, false, StateWaiting, false, true);
                                    recoveredCount++;
                                }
                                else
                                {
                                    Log.Warn("ClusterManager: failed job '" + jKey +
                                             "' no longer exists, cannot schedule recovery.");
                                    otherCount++;
                                }
                            }
                            else
                            {
                                otherCount++;
                            }

                            // free up stateful job's triggers
                            if (ftRec.JobIsStateful)
                            {
                                Delegate.UpdateTriggerStatesForJobFromOtherState(conn, jKey.Name, jKey.Group,
                                                                                 StateWaiting,
                                                                                 StateBlocked);
                                Delegate.UpdateTriggerStatesForJobFromOtherState(conn, jKey.Name, jKey.Group,
                                                                                 StatePaused,
                                                                                 StatePausedBlocked);
                            }
                        }

                        Delegate.DeleteFiredTriggers(conn, rec.SchedulerInstanceId);


                        // Check if any of the fired triggers we just deleted were the last fired trigger
                        // records of a COMPLETE trigger.
                        int completeCount = 0;
                        foreach (Key triggerKey in triggerKeys)
                        {
                            if (
                                Delegate.SelectTriggerState(conn, triggerKey.Name, triggerKey.Group).Equals(
                                    StateComplete))
                            {
                                IList firedTriggers =
                                    Delegate.SelectFiredTriggerRecords(conn, triggerKey.Name, triggerKey.Group);
                                if (firedTriggers.Count == 0)
                                {
                                    SchedulingContext schedulingContext = new SchedulingContext();
                                    schedulingContext.InstanceId = instanceId;

                                    if (RemoveTrigger(conn, schedulingContext, triggerKey.Name, triggerKey.Group))
                                    {
                                        completeCount++;
                                    }
                                }
                            }
                        }
                        LogWarnIfNonZero(acquiredCount,
                                         "ClusterManager: ......Freed " + acquiredCount + " acquired trigger(s).");
                        LogWarnIfNonZero(completeCount,
                                         "ClusterManager: ......Deleted " + completeCount + " complete triggers(s).");
                        LogWarnIfNonZero(recoveredCount,
                                         "ClusterManager: ......Scheduled " + recoveredCount +
                                         " recoverable job(s) for recovery.");
                        LogWarnIfNonZero(otherCount,
                                         "ClusterManager: ......Cleaned-up " + otherCount + " other failed job(s).");


                        if (rec.SchedulerInstanceId.Equals(InstanceId) == false)
                        {
                            Delegate.DeleteSchedulerState(conn, rec.SchedulerInstanceId);
                        }
                    }
                }
                catch (Exception e)
                {
                    throw new JobPersistenceException("Failure recovering jobs: " + e.Message, e);
                }
            }
        }
예제 #33
-1
        protected void Application_Start(object sender, EventArgs e)
        {
            ISchedulerFactory sf = new StdSchedulerFactory();


            DateTime runTime = TriggerUtils.GetEvenMinuteDate(DateTime.UtcNow);
            JobDetail job = new JobDetail("job1", "group1", typeof(HelloJob));
            sched = sf.GetScheduler();
            SimpleTrigger trigger = new SimpleTrigger("trigger1", "group1", runTime);
            sched.ScheduleJob(job, trigger);
 
            sched.Start();
        }