示例#1
0
        private void AddJob(JobGroupNode selectedNode, Action updateAction)
        {
            var frm = new AddJob(mRoot);

            if (frm.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            // add macro
            var selSpecPath = frm.SelectedSpecificationPath;
            var jobData     = new JobDataMap
            {
                { Host.MacroFilePathKey, selSpecPath }
            };
            var jobName = Path.GetFileNameWithoutExtension(selSpecPath);
            var job     = JobBuilder.Create <Host>().
                          WithDescription("TODO extract description from spec"). // TODO extract description from spec
                          WithIdentity(jobName, selectedNode.Name).
                          SetJobData(jobData).
                          StoreDurably().
                          Build();

            mScheduler.AddJob(job, true);
            updateAction();
        }
        public async Task RunJob(JobDefinition jobDefinition, ExecutionEnvironment environment)
        {
            if (scheduler is null)
            {
                throw new InvalidOperationException();
            }
            if (jobDefinition is null)
            {
                throw new ArgumentNullException();
            }

            IJobDetail job = JobBuilder.Create <OrchestrationJob>()
                             .WithIdentity(jobDefinition.Name + "_OnDemand", jobDefinition.Group.GetNameOrDefault())
                             .UsingJobData(OrchestrationJob.UnitCollectionIdPropertyName, jobDefinition.UnitCollectionId)
                             .UsingJobData("JobName", jobDefinition.Name)
                             .StoreDurably()
                             .Build();

            Dictionary <string, string> data = new Dictionary <string, string>();

            data["TriggerName"]      = "__OnDemand";
            data["ConnectionString"] = environment.ConnectionString;
            data["EnvironmentId"]    = environment.Id.ToString();

            JobDataMap jobData = new JobDataMap(data);

            Console.WriteLine($"Registered Trigger {data["TriggerName"]} for job {jobDefinition.Name} in group {jobDefinition.Group}");
            await scheduler.AddJob(job, replace : true);

            await scheduler.TriggerJob(job.Key, jobData);
        }
示例#3
0
        static void Main(string[] args)
        {
            // Create RAMJobStore instance
            DirectSchedulerFactory.Instance.CreateVolatileScheduler(5);
            ISchedulerFactory factory = DirectSchedulerFactory.Instance;

            // Get scheduler and add object
            IScheduler scheduler = factory.GetScheduler();

            StringBuilder history = new StringBuilder("Runtime History: ");

            scheduler.Context.Add("History", history);

            JobKey firstJobKey  = JobKey.Create("FirstJob", "Pipeline");
            JobKey secondJobKey = JobKey.Create("SecondJob", "Pipeline");
            JobKey thirdJobKey  = JobKey.Create("ThirdJob", "Pipeline");

            // Create job and trigger
            IJobDetail firstJob = JobBuilder.Create <FirstJob>()
                                  .WithIdentity(firstJobKey)
                                  //.StoreDurably(true)
                                  .Build();

            IJobDetail secondJob = JobBuilder.Create <SecondJob>()
                                   .WithIdentity(secondJobKey)
                                   .StoreDurably(true)
                                   .Build();

            IJobDetail thirdJob = JobBuilder.Create <ThirdJob>()
                                  .WithIdentity(thirdJobKey)
                                  .StoreDurably(true)
                                  .Build();

            ITrigger firstJobTrigger = TriggerBuilder.Create()
                                       .WithIdentity("Trigger", "Pipeline")
                                       .WithSimpleSchedule(x => x
                                                           .WithMisfireHandlingInstructionFireNow()
                                                           .WithIntervalInSeconds(5)
                                                           .RepeatForever())
                                       .Build();

            JobChainingJobListener listener = new JobChainingJobListener("Pipeline Chain");

            listener.AddJobChainLink(firstJobKey, secondJobKey);
            listener.AddJobChainLink(secondJobKey, thirdJobKey);

            scheduler.ListenerManager.AddJobListener(listener, GroupMatcher <JobKey> .GroupEquals("Pipeline"));

            // Run it all in chain
            scheduler.Start();
            scheduler.ScheduleJob(firstJob, firstJobTrigger);
            scheduler.AddJob(secondJob, false, true);
            scheduler.AddJob(thirdJob, false, true);

            Console.ReadLine();
            scheduler.Shutdown();
            Console.WriteLine("Scheduler shutdown.");
            Console.WriteLine(history);
            Console.ReadLine();
        }
示例#4
0
        /// <summary>
        /// 添加Job
        /// </summary>
        /// <returns></returns>
        public JsonResult AddJob(string jobName, string groupName, string className, string namespaceName, string description)
        {
            try
            {
                //Load(命名空间).GetType(命名空间.类名)
                var type = Assembly.Load(namespaceName).GetType(namespaceName + "." + className);
                if (scheduler.CheckExists(new JobKey(jobName, groupName)) == true)
                {
                    return(Json(new
                    {
                        code = "999999",
                        msg = "该Job已经存在"
                    }));
                }
                var job = JobBuilder.Create(type).StoreDurably(true)
                          .WithDescription(description)
                          .WithIdentity(jobName, groupName)
                          .Build();

                scheduler.AddJob(job, true);
            }
            catch (Exception ex)
            {
                return(Json(new {
                    code = "999999",
                    msg = ex.Message
                }));
            }
            return(Json(new {
                code = "1",
                msg = ""
            }));
        }
示例#5
0
        public static void ScheduleHeartbeatJob(string projectId)
        {
            string    jobName = "Heartbeat_" + projectId;
            JobDetail job     = new JobDetail(jobName, jobName, typeof(HeartbeatJob));

            job.JobDataMap["projectId"] = projectId;

            CronTrigger trigger = new CronTrigger(jobName, jobName, jobName, jobName, FIVE_MINUTE_PATTERN);

            engine.AddJob(job, true);
            DateTime ft = engine.ScheduleJob(trigger);
        }
示例#6
0
        public async Task ExceptionJobUnscheduleFiringTrigger()
        {
            await sched.Start();

            string        jobName  = "ExceptionPolicyUnscheduleFiringTrigger";
            string        jobGroup = "ExceptionPolicyUnscheduleFiringTriggerGroup";
            JobDetailImpl myDesc   = new JobDetailImpl(jobName, jobGroup, typeof(ExceptionJob));

            myDesc.Durable = true;
            await sched.AddJob(myDesc, false);

            string           trigGroup = "ExceptionPolicyFiringTriggerGroup";
            IOperableTrigger trigger   = new CronTriggerImpl("trigName", trigGroup, "0/2 * * * * ?");

            trigger.JobKey = new JobKey(jobName, jobGroup);

            ExceptionJob.ThrowsException         = true;
            ExceptionJob.LaunchCount             = 0;
            ExceptionJob.Refire                  = false;
            ExceptionJob.UnscheduleFiringTrigger = true;
            ExceptionJob.UnscheduleAllTriggers   = false;

            await sched.ScheduleJob(trigger);

            await Task.Delay(7 *1000);

            await sched.DeleteJob(trigger.JobKey);

            Assert.AreEqual(1, ExceptionJob.LaunchCount,
                            "The job shouldn't have been refired (UnscheduleFiringTrigger)");

            ExceptionJob.LaunchCount             = 0;
            ExceptionJob.UnscheduleFiringTrigger = true;
            ExceptionJob.UnscheduleAllTriggers   = false;

            await sched.AddJob(myDesc, false);

            trigger        = new CronTriggerImpl("trigName", trigGroup, "0/2 * * * * ?");
            trigger.JobKey = new JobKey(jobName, jobGroup);
            await sched.ScheduleJob(trigger);

            trigger        = new CronTriggerImpl("trigName1", trigGroup, "0/3 * * * * ?");
            trigger.JobKey = new JobKey(jobName, jobGroup);
            await sched.ScheduleJob(trigger);

            await Task.Delay(7 *1000);

            await sched.DeleteJob(trigger.JobKey);

            Assert.AreEqual(2, ExceptionJob.LaunchCount,
                            "The job shouldn't have been refired(UnscheduleFiringTrigger)");
        }
示例#7
0
        private void buttonEvery2Min_Click(object sender, EventArgs e)
        {
            string message = $"{DateTime.Now.ToLongTimeString()} ---------> Button 2Min click";

            listBox.Items.Add(message);

            // We create a job
            job = JobBuilder.Create <SampleJob>()
                  .StoreDurably(true)
                  .WithIdentity("SampleJob", "SampleGroup")
                  .Build();

            // Only if you want send Complex type parameter to job. Use MergedJobDataMap in the job to get these values
            job.JobDataMap.Put("SampleJobParameters", new SampleJobParameters {
                Control = this
            });

            scheduler.AddJob(job, false).Wait();
            scheduler.ListenerManager.AddJobListener(new SampleJobListener());

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("TriggerButton2", "SampleGroup")
                               .StartNow()
                               .WithCronSchedule("0 0/1 * 1/1 * ? *") // See cronmaker.com. In this example, run job every 2 minutes, any day, any month, any year...
                               .ForJob(job)
                               .Build();

            scheduler.ListenerManager.AddTriggerListener(new SampleTriggerListener());

            scheduler.ScheduleJob(trigger).ContinueWith
            (
                t =>
            {
                var d = t.Result;

                message = $"{DateTime.Now.ToLongTimeString()} - Button 2 click - {d}";
                listBox.Invoke(
                    new Action
                    (
                        () =>
                {
                    listBox.Items.Add(message);
                }
                    )
                    );
            }
            );

            buttonNow.Enabled = true;
        }
        public async Task <IActionResult> Create_schedule(string time, string timem, List <string> list_Idtestcase, int id_url)
        {
            Test_schedule test_Schedule = new Test_schedule();

            test_Schedule.CreatedDate = DateTime.Now;
            string scheduleId = Guid.NewGuid().ToString("N");

            test_Schedule.id_schedule = scheduleId;
            var id_user = _userManager.GetUserId(User);

            test_Schedule.id_user         = id_user;
            test_Schedule.job_repeat_time = time + ":" + timem;
            test_Schedule.status          = "running";
            _context.Test_schedule.Add(test_Schedule);
            await _context.SaveChangesAsync();

            foreach (var id in list_Idtestcase)
            {
                Testcase_scheduled testcase_Scheduled = new Testcase_scheduled();
                testcase_Scheduled.id_schedule = scheduleId;
                testcase_Scheduled.id_url      = id_url;
                testcase_Scheduled.id_testcase = id;

                _context.Testcase_scheduled.Add(testcase_Scheduled);
            }
            _context.SaveChanges();
            IJobDetail job = JobBuilder.Create <RunTestcaseJob>()
                             .UsingJobData("scheduleid", scheduleId)
                             .WithIdentity(scheduleId, id_user)
                             .StoreDurably()
                             .RequestRecovery()
                             .Build();

            await _scheduler.AddJob(job, true);

            ITrigger trigger = TriggerBuilder.Create()
                               .ForJob(job)
                               //.UsingJobData("triggerparam", "Simple trigger 1 Parameter")
                               .WithIdentity(scheduleId + "trigger", id_user)
                               .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(int.Parse(time), int.Parse(timem)))
                               //                                 .StartNow()
                               //                                 .WithSimpleSchedule(z => z.WithIntervalInSeconds(600).RepeatForever())
                               .Build();


            await _scheduler.ScheduleJob(trigger);

            StatusMessage = "Create schedule successfully";
            return(RedirectToAction("Index"));
        }
示例#9
0
        /// <summary>
        /// Initialize Jobs Quartz.Net scheduler
        /// </summary>
        private void ScheduledJobs()
        {
            JobDetailImpl jobDetail = new JobDetailImpl(typeof(MS_JOB_IntegracaoActiveDirectory).Name, typeof(MS_JOB_IntegracaoActiveDirectory));

            jobDetail.Durable = true;
            scheduler.AddJob(jobDetail, true);

            jobDetail         = new JobDetailImpl(typeof(MS_JOB_ExecucaoScriptsFIM).Name, typeof(MS_JOB_ExecucaoScriptsFIM));
            jobDetail.Durable = true;
            scheduler.AddJob(jobDetail, true);

            jobDetail         = new JobDetailImpl(typeof(MS_JOB_ExpiraSenha).Name, typeof(MS_JOB_ExpiraSenha));
            jobDetail.Durable = true;
            scheduler.AddJob(jobDetail, true);
        }
        public async Task <IActionResult> StartSimpleJob()
        {
            var job = JobBuilder.Create <SimpleJob>()
                      // .UsingJobData("username", "devhow")
                      // .UsingJobData("password", "Security!!")
                      .WithIdentity("simplejob", "quartzexamples")
                      .StoreDurably()
                      .Build();

            job.JobDataMap.Put("user", new JobUserParameter {
                Username = "******", Password = "******"
            });

            await _quartzScheduler.AddJob(job, true);

            var trigger = TriggerBuilder.Create()
                          .ForJob(job)
                          .UsingJobData("triggerparam", "Simple trigger 1 parameter")
                          .WithIdentity("testrigger", "quartzexamples")
                          .StartNow()
                          .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).WithRepeatCount(5))
                          // .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(22, 37))
                          // .WithCronSchedule("0 0/1 * 1/1 * ? *")
                          // .WithCalendarIntervalSchedule(x =>
                          //     x.WithIntervalInDays(1)
                          //     .PreserveHourOfDayAcrossDaylightSavings(true)
                          //     .SkipDayIfHourDoesNotExist(true))
                          // .WithDailyTimeIntervalSchedule(x =>
                          //     x.StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(21, 0))
                          //     .EndingDailyAt(TimeOfDay.HourAndMinuteOfDay(22, 0))
                          //     .OnDaysOfTheWeek(DayOfWeek.Thursday)
                          //     .WithIntervalInSeconds(5))
                          // .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(5)).RepeatForever())
                          .Build();

            var trigger2 = TriggerBuilder.Create()
                           .ForJob(job)
                           .UsingJobData("triggerparam", "Simple trigger 1 parameter")
                           .WithIdentity("testrigger2", "quartzexamples")
                           .StartNow()
                           .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).WithRepeatCount(5))
                           .Build();

            var trigger3 = TriggerBuilder.Create()
                           .ForJob(job)
                           .UsingJobData("triggerparam", "Simple trigger 1 parameter")
                           .WithIdentity("testrigger3", "quartzexamples")
                           .StartNow()
                           .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).WithRepeatCount(5))
                           .Build();

            // await _quartzScheduler.ScheduleJob(job, trigger);
            await _quartzScheduler.ScheduleJob(trigger);

            await _quartzScheduler.ScheduleJob(trigger2);

            await _quartzScheduler.ScheduleJob(trigger3);

            return(RedirectToAction("Index"));
        }
示例#11
0
 private void LoadSchedules(LogStatuses status)
 {
     Logger.Log("Loading schedules", status);
     if (!running)
     {
         Logger.Log("Loading schedules aborted. Service is not started.", status);
         return;
     }
     try {
         StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
         scheduler = schedulerFactory.GetScheduler();
         List <BackupScheduleWrapper> jobs = Configuration.GetSchedules();
         foreach (BackupScheduleWrapper bj in jobs)
         {
             JobDetail job = new JobDetail(bj.ID.ToString(), "group1", typeof(MyJobClass));
             try {
                 CronTrigger trigger = new CronTrigger("trigger {0}".FillBlanks(bj.ID), "group1", bj.ID.ToString(), "group1", bj.CronConfig);
                 scheduler.AddJob(job, true);
                 scheduler.ScheduleJob(trigger);
                 Logger.Log(string.Format("Job {0} ({1}) added to schedule", bj.ID, bj.Name), LogStatuses.Message);
             } catch (Exception ex) {
                 Logger.Log(string.Format("Error adding job {0} ({1}) to schedule: {2}", bj.ID, bj.Name, ex.Message), LogStatuses.Error);
             }
         }
         scheduler.Start();
     } catch (Exception oEx) {
         Logger.Log(string.Format("Error scheduling jobs: {0}", oEx.Message), LogStatuses.Error);
     }
 }
示例#12
0
        public void TestStartupAndStop()
        {
            Logger.WriteEntry("Starting Service Weather");
            try
            {
                ISchedulerFactory schedFact = new StdSchedulerFactory();
                sched = schedFact.GetScheduler();

                IJobDetail job = JobBuilder.Create <WeatherJob>()
                                 .WithIdentity("WeatherJob", "Weathergroup")
                                 .StoreDurably()
                                 .Build();

                sched.AddJob(job, true);

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("Weatherrigger", "WeatherGroup")
                                   .StartNow()
                                   .WithSimpleSchedule(x => x
                                                       .WithIntervalInMinutes(Convert.ToInt32(ConfigurationManager.AppSettings["MinuteInterval"].ToString()))
                                                       .RepeatForever())
                                   .ForJob(job)
                                   .Build();


                sched.ScheduleJob(trigger);

                sched.Start();
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
        }
示例#13
0
        public static async Task MaybeRegister <T>(IScheduler scheduler, T job) where T : ISelfDescribingJob
        {
            //var description = job.Describe;
            //var jobKey = new JobKey(description.JobName, description.JobGroup);

            //if (await scheduler.CheckExists(jobKey)) return;


            //var jobDetail = JobBuilder.Create<T>()
            //    .WithIdentity(description.JobName, description.JobGroup)
            //    .StoreDurably()
            //    .Build();

            //var jobTrigger = TriggerBuilder.Create()
            //    .WithIdentity(description.JobName, description.JobGroup)
            //    .WithSimpleSchedule(job.Cron)

            //    .StartAt(DateTime.Now)
            //    .Build();

            //await scheduler.ScheduleJob(jobDetail, jobTrigger);


            // get the job description
            var description       = job.Describe;
            var hasActiveSchedule = description.HasActiveSchedule;

            // form the job key
            var jobKey = new JobKey(description.JobName, description.JobGroup);

            // check that the job is not yet registered in quartz (remember we store them in db)
            if (await scheduler.CheckExists(jobKey))
            {
                return;
            }

            // create the jobdetail with the identity (job name/group description pair)
            var jobDetail = JobBuilder.Create <T>()
                            .WithIdentity(description.JobName, description.JobGroup)
                            .StoreDurably()
                            .Build();

            if (hasActiveSchedule)
            {
                // create the job trigger with the CRON schedule
                var trigger = TriggerBuilder.Create()
                              .WithIdentity(description.JobName, description.JobGroup)
                              .WithSimpleSchedule(job.Cron)

                              .StartAt(DateTime.Now)
                              .Build();

                // throw it into quartz's direction.
                await scheduler.ScheduleJob(jobDetail, trigger);
            }
            else
            {
                await scheduler.AddJob(jobDetail, true);
            }
        }
        protected void Application_Start(object sender, EventArgs e)
        {
            //控制台就放在Main
            logger.Debug("Application_Start");
            log4net.Config.XmlConfigurator.Configure();
            //从配置中读取任务启动时间
            int indexStartHour = Convert.ToInt32(ConfigurationManager.AppSettings["IndexStartHour"]);
            int indexStartMin  = Convert.ToInt32(ConfigurationManager.AppSettings["IndexStartMin"]);


            ISchedulerFactory sf = new StdSchedulerFactory();

            sched = sf.GetScheduler();
            JobDetail job     = new JobDetail("job1", "group1", typeof(IndexJob));                       //IndexJob为实现了IJob接口的类
            Trigger   trigger = TriggerUtils.MakeDailyTrigger("tigger1", indexStartHour, indexStartMin); //每天10点3分执行

            trigger.JobName  = "job1";
            trigger.JobGroup = "group1";
            trigger.Group    = "group1";

            sched.AddJob(job, true);
            sched.ScheduleJob(trigger);
            //IIS启动了就不会来了
            sched.Start();
        }
示例#15
0
        public async Task Execute(IJobExecutionContext context)
        {
            _logger.LogInformation("Hello world!");
            //Console.WriteLine("Hello world!");
            var listSchedule = _context.Test_schedule.Where(p => p.status.ToLower().Equals("running")).ToList();

            foreach (var schedule in listSchedule)
            {
                IJobDetail job = JobBuilder.Create <RunTestcaseJob>()
                                 .UsingJobData("scheduleid", schedule.id_schedule)
                                 .WithIdentity(schedule.id_schedule, schedule.id_user)
                                 .StoreDurably()
                                 .RequestRecovery()
                                 .Build();

                await _scheduler.AddJob(job, true);

                ITrigger trigger = TriggerBuilder.Create()
                                   .ForJob(job)
                                   //.UsingJobData("triggerparam", "Simple trigger 1 Parameter")
                                   .WithIdentity(schedule.id_schedule + "trigger", schedule.id_user)
                                   .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(16, 25))
                                   //.StartNow()
                                   //.WithSimpleSchedule(z => z.WithIntervalInSeconds(10).RepeatForever())
                                   .Build();


                await _scheduler.ScheduleJob(trigger);
            }
        }
示例#16
0
文件: Form1.cs 项目: radtek/Bummer
        public Form1()
        {
            InitializeComponent();
            // Instantiate the Quartz.NET scheduler
            StdSchedulerFactory schedulerFactory = new StdSchedulerFactory();
            IScheduler          scheduler        = schedulerFactory.GetScheduler();

            // Instantiate the JobDetail object passing in the type of your
            // custom job class. Your class merely needs to implement a simple
            // interface with a single method called "Execute".
            JobDetail job = new JobDetail("job1", "group1", typeof(MyJobClass));

            DateTime    now     = DateTime.Now.AddMinutes(1);
            DateTime    dt      = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
            CronTrigger trigger = new CronTrigger("trigger 1", "group1", "job1", "group1", "5 * * * * ?");

            //CronTrigger ct = new CronTrigger( "trigger 1", "group1", "job1", "group1", "5 * * * * ?" );
            //SimpleTrigger trigger = new SimpleTrigger( "trigger 1", new DateTime( dt.ToFileTimeUtc() ), null, SimpleTrigger.RepeatIndefinitely, new TimeSpan( 0, 0, 0, 15 ) );
            //trigger.JobName = "job1";
            //trigger.Group = "group1";
            //trigger.JobGroup = "group1";
            // Instantiate a trigger using the basic cron syntax.
            // This tells it to run at 1AM every Monday - Friday.
            // Add the job to the scheduler
            scheduler.AddJob(job, true);
            scheduler.ScheduleJob(trigger);
            scheduler.Start();
        }
示例#17
0
        public static async void Start()
        {
            IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler();

            var job = JobBuilder.Create <ValuesController>()
                      .StoreDurably(true)
                      .WithIdentity("send-telegram-message")
                      .Build();

            await scheduler.AddJob(job, false);

            var trigger1 = TriggerBuilder.Create()
                           .ForJob(job)
                           .WithIdentity("trigger1")
                           .WithSchedule(CronScheduleBuilder
                                         .DailyAtHourAndMinute(12, 00)
                                         .InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Middle East Standard Time")))
                           .Build();


            await scheduler.ScheduleJob(trigger1);


            var trigger2 = TriggerBuilder.Create()
                           .ForJob(job)
                           .WithIdentity("trigger2")
                           .WithSchedule(CronScheduleBuilder
                                         .DailyAtHourAndMinute(23, 00)
                                         .InTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Middle East Standard Time")))
                           .Build();

            await scheduler.ScheduleJob(trigger2);

            await scheduler.Start();
        }
示例#18
0
        /// <summary>
        /// Create new job of type <see cref="jobType"/> without any triggers
        /// </summary>
        /// <param name="jobName"></param>
        /// <param name="jobGroup"></param>
        /// <param name="jobType"></param>
        /// <param name="dataMap"><see cref="jobType"/> specific parameters</param>
        /// <param name="description"></param>
        public void CreateJob(string jobName, string jobGroup, Type jobType, Dictionary <string, object> dataMap, string description)
        {
            if (jobName.Contains("/") ||
                (!string.IsNullOrEmpty(jobGroup) && jobGroup.Contains("/")) ||
                jobName.Contains("\\") ||
                (!string.IsNullOrEmpty(jobGroup) && jobGroup.Contains("\\")))
            {
                throw new Exception(@"JobName and JobGroup cannot contain '/' (forward slash) or '\' (back slash)");
            }

            // Use DefaultGroup if jobGroup is null or empty
            jobGroup = (!string.IsNullOrEmpty(jobGroup)) ? jobGroup : JobKey.DefaultGroup;

            var        jobbuilder = JobBuilder.Create(jobType);
            IJobDetail jobDetail  = jobbuilder.WithDescription(description)
                                    .WithIdentity(jobName, jobGroup).StoreDurably(true).RequestRecovery(false)
                                    .Build();

            //IJobDetail jobDetail = new JobDetailImpl(jobName, jobGroup, jobType, true, false);
            foreach (var mapItem in dataMap)
            {
                jobDetail.JobDataMap.Add(mapItem.Key, mapItem.Value);
            }

            _scheduler.AddJob(jobDetail, true);
        }
示例#19
0
        /// <summary>
        /// Create new job of type <see cref="jobType"/> without any triggers
        /// </summary>
        /// <param name="jobName"></param>
        /// <param name="jobGroup"></param>
        /// <param name="jobType"></param>
        /// <param name="dataMap"><see cref="jobType"/> specific parameters</param>
        /// <param name="description"></param>
        /// <param name="jobId"></param>
        public Guid CreateJob(string jobName, string jobGroup, Type jobType, Dictionary <string, object> dataMap, string description, Guid?jobId = null)
        {
            // Use DefaultGroup if jobGroup is null or empty
            jobGroup = (!string.IsNullOrEmpty(jobGroup)) ? jobGroup : JobKey.DefaultGroup;

            var        jobbuilder = JobBuilder.Create(jobType);
            IJobDetail jobDetail  = jobbuilder.WithDescription(description)
                                    .WithIdentity(jobName, jobGroup).StoreDurably(true).RequestRecovery(false)
                                    .Build();

            foreach (var mapItem in dataMap)
            {
                jobDetail.JobDataMap.Add(mapItem.Key, mapItem.Value);
            }

            Guid id;

            using (var tran = new TransactionScope())
            {
                id = _persistanceStore.UpsertJobKeyIdMap(jobName, jobGroup, jobId);
                _scheduler.AddJob(jobDetail, true);
                tran.Complete();
            }

            return(id);
        }
        private async Task Run()
        {
            try
            {
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
                StdSchedulerFactory factory = new StdSchedulerFactory(props);
                Scheduler = await factory.GetScheduler();

                await Scheduler.Start();

                var jobs = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IJob)))).ToArray();
                foreach (var job in jobs)
                {
                    Scheduler.AddJob(job);
                }

                //Jobs.Jobs.Config(Scheduler);
            }
            catch (SchedulerException ex)
            {
                LogHelper.SaveLog(ex);
            }
        }
示例#21
0
        public async Task <bool> AddTrigger(string triggerKey, string url, string cron)
        {
            var jobKey = JobKey.Create(JobConfig.JobName, JobConfig.JobGroup);
            var job    = await _scheduler.GetJobDetail(jobKey);

            if (job == null)
            {
                job = JobBuilder.Create <CallingApiService>()
                      .WithIdentity(jobKey)
                      .StoreDurably(true)
                      .Build();
                await _scheduler.AddJob(job, false);
            }
            else
            {
                await _scheduler.ResumeJob(jobKey);
            }
            var trigger = TriggerBuilder.Create()
                          .WithIdentity(triggerKey, TriggerKey.DefaultGroup)
                          .UsingJobData(JobConfig.TriggerJobDataKey, url)
                          .StartNow()
                          .ForJob(jobKey)
                          .WithCronSchedule(cron)
                          .Build();

            await _scheduler.ScheduleJob(trigger);

            return(true);
        }
示例#22
0
        [Route("")][HttpPost]  public async Task <IActionResult> StartSimpleJob()
        {
            var simpleJobDetail = JobBuilder.Create <SimpleJob>().UsingJobData("username", "some data").UsingJobData("password", "somePass").WithIdentity(nameof(SimpleJob), "Jobs").StoreDurably().Build();

            simpleJobDetail.JobDataMap.Put("user", new SimpleJobParameter
            {
                Username = "******",
                Password = "******"
            });
            //save the job
            await _scheduler.AddJob(simpleJobDetail, true);



            ITrigger trigger = TriggerBuilder.Create()
                               .ForJob(simpleJobDetail)
                               .UsingJobData("triggerparam", "Simple trigger 1 Parameter")
                               .WithIdentity("testtrigger", "Jobs")
                               .StartNow()
                               .WithSimpleSchedule(z => z.WithIntervalInSeconds(5).RepeatForever())
                               .Build();

            await _scheduler.ScheduleJob(trigger);

            return(Ok(simpleJobDetail));
        }
示例#23
0
        public async Task TestShutdownWithoutWaitIsUnclean()
        {
            List <DateTime> jobExecTimestamps = new List <DateTime>();
            Barrier         barrier           = new Barrier(2);
            IScheduler      scheduler         = await CreateScheduler("testShutdownWithoutWaitIsUnclean", 8);

            try
            {
                scheduler.Context.Put(Barrier, barrier);
                scheduler.Context.Put(DateStamps, jobExecTimestamps);
                await scheduler.Start();

                string jobName = Guid.NewGuid().ToString();
                await scheduler.AddJob(JobBuilder.Create <TestJobWithSync>().WithIdentity(jobName).StoreDurably().Build(), false);

                await scheduler.ScheduleJob(TriggerBuilder.Create().ForJob(jobName).StartNow().Build());

                while ((await scheduler.GetCurrentlyExecutingJobs()).Count == 0)
                {
                    await Task.Delay(50);
                }
            }
            finally
            {
                await scheduler.Shutdown(false);
            }

            barrier.SignalAndWait(testTimeout);
        }
示例#24
0
        public async Task TestAbilityToFireImmediatelyWhenStartedBeforeWithTriggerJob()
        {
            List <DateTime> jobExecTimestamps = new List <DateTime>();
            Barrier         barrier           = new Barrier(2);

            IScheduler sched = await CreateScheduler("testAbilityToFireImmediatelyWhenStartedBeforeWithTriggerJob", 5);

            await sched.Clear();

            sched.Context.Put(Barrier, barrier);
            sched.Context.Put(DateStamps, jobExecTimestamps);

            await sched.Start();

            IJobDetail job1 = JobBuilder.Create <TestJobWithSync>()
                              .WithIdentity("job1").
                              StoreDurably().Build();
            await sched.AddJob(job1, false);

            DateTime sTime = DateTime.UtcNow;

            await sched.TriggerJob(job1.Key);

            barrier.SignalAndWait(testTimeout);

            await sched.Shutdown(false);

            DateTime fTime = jobExecTimestamps[0];

            Assert.That(fTime - sTime < TimeSpan.FromMilliseconds(7000), "Immediate trigger did not fire within a reasonable amount of time."); // This is dangerously subjective!  but what else to do?
        }
示例#25
0
        public void Execute_a_job()
        {
            // Arrange
            // - Add a job into the test scheduler
            IScheduler sched = GetTestScheduler();
            JobDetail  job   = new JobDetail("TestJob", "TestGroup", typeof(Quartz.Job.NoOpJob));

            sched.AddJob(job, true);
            // - Setup the mock HTTP Request
            var request = new Mock <System.Web.HttpRequestBase>();
            var context = new Mock <System.Web.HttpContextBase>();

            context.SetupGet(x => x.Request).Returns(request.Object);
            System.Collections.Specialized.NameValueCollection formParameters = new System.Collections.Specialized.NameValueCollection();
            // NOTE: adding items to the formParameter collection is possible here
            request.SetupGet(x => x.Form).Returns(formParameters);


            // - Create the fake instance repo and the job execution controller
            QuartzAdmin.web.Models.IInstanceRepository instanceRepo = new Fakes.FakeInstanceRepository();
            instanceRepo.Save(GetTestInstance());
            QuartzAdmin.web.Controllers.JobExecutionController jec = new QuartzAdmin.web.Controllers.JobExecutionController(instanceRepo);

            // - Set the fake request for the controller
            jec.ControllerContext = new System.Web.Mvc.ControllerContext(context.Object, new System.Web.Routing.RouteData(), jec);

            // Act
            System.Web.Mvc.ActionResult result = jec.RunNow("MyTestInstance", "TestGroup", "TestJob");

            //Assert
            Assert.IsTrue(result is System.Web.Mvc.ContentResult && ((System.Web.Mvc.ContentResult)result).Content == "Job execution started");
        }
示例#26
0
        private static void EventNotificationScheduler()
        {
            SMCHDBEntities _entities = new SMCHDBEntities();

            //Get list of dates
            DateTime      today          = DateTime.Today;
            String        jobName        = "EventNotificationJob";
            List <Event>  eventList      = _entities.Events.Where(a => a.RegistrationOpenDate >= today).ToList();
            JobDetailImpl eventJobDetail = new JobDetailImpl(jobName, typeof(EventEmailJob));

            sched.AddJob(eventJobDetail, true);

            foreach (Event eventEntry in eventList)
            {
                SimpleTriggerImpl trigger = new SimpleTriggerImpl(eventEntry.Title + "_EventTrigger", eventEntry.RegistrationOpenDate.ToUniversalTime());

                trigger.JobDataMap["eventName"]      = eventEntry.Title;
                trigger.JobDataMap["eventStartTime"] = eventEntry.StartDateTime;
                trigger.JobDataMap["eventEndTime"]   = eventEntry.EndDateTime;
                trigger.JobDataMap["regStartTime"]   = eventEntry.RegistrationOpenDate;
                trigger.JobDataMap["regEndTime"]     = eventEntry.RegistrationCloseDate;

                trigger.JobName = jobName;
                sched.ScheduleJob(trigger);
            }
        }
示例#27
0
        public async Task AddJob(string schedulerName, string jobGroup, string jobName, string jobType, bool durable, bool requestsRecovery, bool replace = false)
        {
            IScheduler scheduler = await GetScheduler(schedulerName).ConfigureAwait(false);

            var jobDetail = new JobDetailImpl(jobName, jobGroup, Type.GetType(jobType), durable, requestsRecovery);
            await scheduler.AddJob(jobDetail, replace).ConfigureAwait(false);
        }
示例#28
0
        public async Task <JobController> Constructor(Config config)
        {
            var tasks = new List <Task>();
            int index = 0;

            var jobStates = (Dictionary <JobKey, UploadJobState>)scheduler.Context["states"];

            foreach (var cfgJog in config.Jobs)
            {
                var jobValidEx = cfgJog.Validate();
                if (jobValidEx != null)
                {
                    throw jobValidEx;
                }

                var data = new JobDataMap
                {
                    ["index"] = index,
                    ["data"]  = cfgJog
                };

                var job = JobBuilder.Create <UploadJob>()
                          .WithIdentity(cfgJog.Name)
                          .UsingJobData(data)
                          .StoreDurably(true)
                          .Build();

                jobStates.Add(job.Key, new UploadJobState());

                if (!string.IsNullOrEmpty(cfgJog.CronSchedule)) // Задача по расписанию Cron
                {
                    var trigger = TriggerBuilder.Create()
                                  .WithIdentity(cfgJog.Name)
                                  .WithCronSchedule(cfgJog.CronSchedule)
                                  .StartNow()
                                  .Build();

                    var task = scheduler.ScheduleJob(job, trigger);
                    tasks.Add(task);
                }
                else if (!string.IsNullOrEmpty(cfgJog.RunAfter))   // Задача запускаемая после другой задачи
                {
                    var afterKey = JobKey.Create(cfgJog.RunAfter);
                    if (!runAfter.ContainsKey(afterKey))
                    {
                        runAfter[afterKey] = new List <JobKey>();
                    }
                    runAfter[afterKey].Add(job.Key);

                    var task = scheduler.AddJob(job, true);
                    tasks.Add(task);
                }

                index++;
            }

            await Task.WhenAll(tasks);

            return(this);
        }
示例#29
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)
        }
示例#30
0
        public void ScheduleTask(ScheduledTask task)
        {
            if (task.ScheduledTaskId == default(long))
            {
                throw new ArgumentException("Scheduling a task requires the task to be saved to the database and have a ScheduledTaskId assigned.");
            }

            JobKey     jobKey = JobKey.Create(task.TaskName, JobKey.DefaultGroup);
            IJobDetail job;

            if (!m_QuartzScheduler.CheckExists(jobKey))
            {
                JobDataMap jobDataMap = new JobDataMap();
                jobDataMap.Add("connectionString", m_Controller.ConnectionString);
                jobDataMap.Add("threadSynchronizer", m_ThreadSynchronizer);
                jobDataMap.Add("scheduledTaskId", task.ScheduledTaskId);

                job = JobBuilder.Create <ExecuteSequenceJob>()
                      .WithIdentity(jobKey)
                      .SetJobData(jobDataMap)
                      .StoreDurably()
                      .Build();
                m_QuartzScheduler.AddJob(job, false);

                ExecuteSequenceJobListener jobListener = new ExecuteSequenceJobListener(task.TaskName);
                jobListener.TaskStart    += jobListener_TaskStart;
                jobListener.TaskComplete += jobListener_TaskComplete;
                m_QuartzScheduler.ListenerManager.AddJobListener(jobListener, KeyMatcher <JobKey> .KeyEquals(jobKey));
            }
            else
            {
                job = m_QuartzScheduler.GetJobDetail(jobKey);
                m_QuartzScheduler.UnscheduleJobs(m_QuartzScheduler.GetTriggersOfJob(jobKey)
                                                 .Select(t => t.Key)
                                                 .ToList());
            }

            if (task.Enabled)
            {
                task.NextScheduledRunTimeUtc = DateTime.MaxValue;
                foreach (TriggerBuilder triggerBuilder in TriggerBuilderFactory.CreateForSchedule(task.TaskName, task.RunSchedule))
                {
                    ITrigger trigger = triggerBuilder
                                       .ForJob(job)
                                       .Build();
                    DateTimeOffset nextScheduledRunTimeUtc = m_QuartzScheduler.ScheduleJob(trigger);
                    if (nextScheduledRunTimeUtc.DateTime < task.NextScheduledRunTimeUtc.Value)
                    {
                        task.NextScheduledRunTimeUtc = nextScheduledRunTimeUtc.DateTime;
                    }
                }
            }
            else
            {
                task.NextScheduledRunTimeUtc = null;
            }

            m_Controller.SetScheduledTaskNextScheduledRunTime(task.ScheduledTaskId, task.NextScheduledRunTimeUtc);
        }
示例#31
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);
        }
示例#32
0
        public MonitorService()
        {
            this.ServiceName = "Sharp Monitoring Service";

            // create the job to be scheduled
            Type jobType = typeof(DailyTask);
            JobDetail job = new JobDetail(jobType.Name, null, jobType);

            ISchedulerFactory schedFact = new StdSchedulerFactory();
            sched = schedFact.GetScheduler();
            sched.Start();

            // schedule daily cron job
            Trigger trigger = new CronTrigger("CronTrigger", null, jobType.Name, null, SharpMonitor.Properties.Settings.Default.CornExpression);
            sched.AddJob(job, true);

            DateTime ft = sched.ScheduleJob(trigger);

            // start job immediately if next schedule job is tomorrow
            if (ft > DateTime.UtcNow)
            {
                sched.TriggerJob(jobType.Name, null);
            }
        }
示例#33
0
        private void TestMatchers(IScheduler scheduler)
        {
            scheduler.Clear();

            IJobDetail job = JobBuilder.Create<NoOpJob>().WithIdentity("job1", "aaabbbccc").StoreDurably().Build();
            scheduler.AddJob(job, true);
            SimpleScheduleBuilder schedule = SimpleScheduleBuilder.Create();
            ITrigger trigger = TriggerBuilder.Create().WithIdentity("trig1", "aaabbbccc").WithSchedule(schedule).ForJob(job).Build();
            scheduler.ScheduleJob(trigger);

            job = JobBuilder.Create<NoOpJob>().WithIdentity("job1", "xxxyyyzzz").StoreDurably().Build();
            scheduler.AddJob(job, true);
            schedule = SimpleScheduleBuilder.Create();
            trigger = TriggerBuilder.Create().WithIdentity("trig1", "xxxyyyzzz").WithSchedule(schedule).ForJob(job).Build();
            scheduler.ScheduleJob(trigger);

            job = JobBuilder.Create<NoOpJob>().WithIdentity("job2", "xxxyyyzzz").StoreDurably().Build();
            scheduler.AddJob(job, true);
            schedule = SimpleScheduleBuilder.Create();
            trigger = TriggerBuilder.Create().WithIdentity("trig2", "xxxyyyzzz").WithSchedule(schedule).ForJob(job).Build();
            scheduler.ScheduleJob(trigger);

            Collection.ISet<JobKey> jkeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.AnyGroup());
            Assert.That(jkeys.Count, Is.EqualTo(3), "Wrong number of jobs found by anything matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("xxxyyyzzz"));
            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by equals matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("aaabbbccc"));
            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by equals matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupStartsWith("aa"));
            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by starts with matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupStartsWith("xx"));
            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by starts with matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEndsWith("cc"));
            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by ends with matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEndsWith("zzz"));
            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by ends with matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupContains("bc"));
            Assert.That(jkeys.Count, Is.EqualTo(1), "Wrong number of jobs found by contains with matcher");

            jkeys = scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupContains("yz"));
            Assert.That(jkeys.Count, Is.EqualTo(2), "Wrong number of jobs found by contains with matcher");

            Collection.ISet<TriggerKey> tkeys = scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.AnyGroup());
            Assert.That(tkeys.Count, Is.EqualTo(3), "Wrong number of triggers found by anything matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("xxxyyyzzz"));
            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by equals matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("aaabbbccc"));
            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by equals matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupStartsWith("aa"));
            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by starts with matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupStartsWith("xx"));
            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by starts with matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEndsWith("cc"));
            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by ends with matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEndsWith("zzz"));
            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by ends with matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupContains("bc"));
            Assert.That(tkeys.Count, Is.EqualTo(1), "Wrong number of triggers found by contains with matcher");

            tkeys = scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupContains("yz"));
            Assert.That(tkeys.Count, Is.EqualTo(2), "Wrong number of triggers found by contains with matcher");
        }
		/// <summary>
		/// Schedules a given job and trigger (both wrapped by a <see cref="JobSchedulingBundle" />).
		/// </summary>
		/// <param name="job">The job.</param>
		/// <param name="sched">The sched.</param>
		/// <param name="localOverWriteExistingJobs">if set to <c>true</c> [local over write existing jobs].</param>
		/// <exception cref="SchedulerException"> 
		/// if the Job or Trigger cannot be added to the Scheduler, or
		/// there is an internal Scheduler error.
		/// </exception>
		public virtual void ScheduleJob(JobSchedulingBundle job, IScheduler sched, bool localOverWriteExistingJobs)
		{
			if ((job != null) && job.Valid)
			{
				JobDetail detail = job.JobDetail;

				JobDetail dupeJ = sched.GetJobDetail(detail.Name, detail.Group);

				if ((dupeJ != null) && !localOverWriteExistingJobs)
				{
					Log.Info("Not overwriting existing job: " + dupeJ.FullName);
					return;
				}

				if (dupeJ != null)
				{
					Log.Info(string.Format(CultureInfo.InvariantCulture, "Replacing job: {0}", detail.FullName));
				}
				else
				{
					Log.Info(string.Format(CultureInfo.InvariantCulture, "Adding job: {0}", detail.FullName));
				}

				if (job.Triggers.Count == 0 && !job.JobDetail.Durable)
				{
					throw new SchedulerException("A Job defined without any triggers must be durable");
				}
				
				sched.AddJob(detail, true);

					
				foreach(Trigger trigger in job.Triggers)
				{
					Trigger dupeT = sched.GetTrigger(trigger.Name, trigger.Group);

					trigger.JobName = detail.Name;
					trigger.JobGroup = detail.Group;

					if (trigger.StartTimeUtc == DateTime.MinValue)
					{
						trigger.StartTimeUtc = DateTime.UtcNow;
					}

					if (dupeT != null)
					{
						Log.Debug(string.Format(CultureInfo.InvariantCulture, "Rescheduling job: {0} with updated trigger: {1}", detail.FullName, trigger.FullName));
						if (!dupeT.JobGroup.Equals(trigger.JobGroup) || !dupeT.JobName.Equals(trigger.JobName))
						{
							Log.Warn("Possibly duplicately named triggers in jobs xml file!");
						}
						sched.RescheduleJob(trigger.Name, trigger.Group, trigger);
					}
					else
					{
						Log.Debug(string.Format(CultureInfo.InvariantCulture, "Scheduling job: {0} with trigger: {1}", detail.FullName, trigger.FullName));
						sched.ScheduleJob(trigger);
					}
				}

				AddScheduledJob(job);
			}
		}
示例#35
0
        public void Test(IScheduler scheduler, bool clearJobs, bool scheduleJobs)
        {
            try
               {
               if (clearJobs)
               {
                   scheduler.Clear();
               }

               if (scheduleJobs)
               {
                   ICalendar cronCalendar = new CronCalendar("0/5 * * * * ?");
                   ICalendar holidayCalendar = new HolidayCalendar();

                   // QRTZNET-86
                   ITrigger t = scheduler.GetTrigger(new TriggerKey("NonExistingTrigger", "NonExistingGroup"));
                   Assert.IsNull(t);

                   AnnualCalendar cal = new AnnualCalendar();
                   scheduler.AddCalendar("annualCalendar", cal, false, true);

                   IOperableTrigger calendarsTrigger = new SimpleTriggerImpl("calendarsTrigger", "test", 20, TimeSpan.FromMilliseconds(5));
                   calendarsTrigger.CalendarName = "annualCalendar";

                   JobDetailImpl jd = new JobDetailImpl("testJob", "test", typeof(NoOpJob));
                   scheduler.ScheduleJob(jd, calendarsTrigger);

                   // QRTZNET-93
                   scheduler.AddCalendar("annualCalendar", cal, true, true);

                   scheduler.AddCalendar("baseCalendar", new BaseCalendar(), false, true);
                   scheduler.AddCalendar("cronCalendar", cronCalendar, false, true);
                   scheduler.AddCalendar("dailyCalendar", new DailyCalendar(DateTime.Now.Date, DateTime.Now.AddMinutes(1)), false, true);
                   scheduler.AddCalendar("holidayCalendar", holidayCalendar, false, true);
                   scheduler.AddCalendar("monthlyCalendar", new MonthlyCalendar(), false, true);
                   scheduler.AddCalendar("weeklyCalendar", new WeeklyCalendar(), false, true);

                   scheduler.AddCalendar("cronCalendar", cronCalendar, true, true);
                   scheduler.AddCalendar("holidayCalendar", holidayCalendar, true, true);

                   Assert.IsNotNull(scheduler.GetCalendar("annualCalendar"));

                   JobDetailImpl lonelyJob = new JobDetailImpl("lonelyJob", "lonelyGroup", typeof(SimpleRecoveryJob));
                   lonelyJob.Durable = true;
                   lonelyJob.RequestsRecovery = true;
                   scheduler.AddJob(lonelyJob, false);
                   scheduler.AddJob(lonelyJob, true);

                   string schedId = scheduler.SchedulerInstanceId;

                   int count = 1;

                   JobDetailImpl job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));

                   // ask scheduler to re-Execute this job if it was in progress when
                   // the scheduler went down...
                   job.RequestsRecovery = true;
                   IOperableTrigger trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));
                   trigger.JobDataMap.Add("key", "value");
                   trigger.EndTimeUtc = DateTime.UtcNow.AddYears(10);

                   trigger.StartTimeUtc = DateTime.Now.AddMilliseconds(1000L);
                   scheduler.ScheduleJob(job, trigger);

                   // check that trigger was stored
                   ITrigger persisted = scheduler.GetTrigger(new TriggerKey("trig_" + count, schedId));
                   Assert.IsNotNull(persisted);
                   Assert.IsTrue(persisted is SimpleTriggerImpl);

                   count++;
                   job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                   // ask scheduler to re-Execute this job if it was in progress when
                   // the scheduler went down...
                   job.RequestsRecovery = (true);
                   trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(5));

                   trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(2000L));
                   scheduler.ScheduleJob(job, trigger);

                   count++;
                   job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryStatefulJob));
                   // ask scheduler to re-Execute this job if it was in progress when
                   // the scheduler went down...
                   job.RequestsRecovery = (true);
                   trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(3));

                   trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                   scheduler.ScheduleJob(job, trigger);

                   count++;
                   job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                   // ask scheduler to re-Execute this job if it was in progress when
                   // the scheduler went down...
                   job.RequestsRecovery = (true);
                   trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromSeconds(4));

                   trigger.StartTimeUtc = (DateTime.Now.AddMilliseconds(1000L));
                   scheduler.ScheduleJob(job, trigger);

                   count++;
                   job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                   // ask scheduler to re-Execute this job if it was in progress when
                   // the scheduler went down...
                   job.RequestsRecovery = (true);
                   trigger = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                   scheduler.ScheduleJob(job, trigger);

                   count++;
                   job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                   // ask scheduler to re-Execute this job if it was in progress when
                   // the scheduler went down...
                   job.RequestsRecovery = (true);
                   IOperableTrigger ct = new CronTriggerImpl("cron_trig_" + count, schedId, "0/10 * * * * ?");
                   ct.JobDataMap.Add("key", "value");
                   ct.StartTimeUtc = DateTime.Now.AddMilliseconds(1000);

                   scheduler.ScheduleJob(job, ct);

                   count++;
                   job = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                   // ask scheduler to re-Execute this job if it was in progress when
                   // the scheduler went down...
                   job.RequestsRecovery = (true);
                   DailyTimeIntervalTriggerImpl nt = new DailyTimeIntervalTriggerImpl("nth_trig_" + count, schedId, new TimeOfDay(1, 1, 1), new TimeOfDay(23, 30, 0), IntervalUnit.Hour, 1);
                   nt.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);

                   scheduler.ScheduleJob(job, nt);

                   DailyTimeIntervalTriggerImpl nt2 = new DailyTimeIntervalTriggerImpl();
                   nt2.Key = new TriggerKey("nth_trig2_" + count, schedId);
                   nt2.StartTimeUtc = DateTime.Now.Date.AddMilliseconds(1000);
                   nt2.JobKey = job.Key;
                   scheduler.ScheduleJob(nt2);

                   // GitHub issue #92
                   scheduler.GetTrigger(nt2.Key);

                   // GitHub issue #98
                   nt2.StartTimeOfDay = new TimeOfDay(1, 2, 3);
                   nt2.EndTimeOfDay = new TimeOfDay(2, 3, 4);

                   scheduler.UnscheduleJob(nt2.Key);
                   scheduler.ScheduleJob(nt2);

                   var triggerFromDb = (IDailyTimeIntervalTrigger) scheduler.GetTrigger(nt2.Key);
                   Assert.That(triggerFromDb.StartTimeOfDay.Hour, Is.EqualTo(1));
                   Assert.That(triggerFromDb.StartTimeOfDay.Minute, Is.EqualTo(2));
                   Assert.That(triggerFromDb.StartTimeOfDay.Second, Is.EqualTo(3));

                   Assert.That(triggerFromDb.EndTimeOfDay.Hour, Is.EqualTo(2));
                   Assert.That(triggerFromDb.EndTimeOfDay.Minute, Is.EqualTo(3));
                   Assert.That(triggerFromDb.EndTimeOfDay.Second, Is.EqualTo(4));

                   job.RequestsRecovery = (true);
                   CalendarIntervalTriggerImpl intervalTrigger = new CalendarIntervalTriggerImpl(
                       "calint_trig_" + count,
                       schedId,
                       DateTime.UtcNow.AddMilliseconds(300),
                       DateTime.UtcNow.AddMinutes(1),
                       IntervalUnit.Second,
                       8);
                   intervalTrigger.JobKey = job.Key;

                   scheduler.ScheduleJob(intervalTrigger);

                   // bulk operations
                   var info = new Dictionary<IJobDetail, Collection.ISet<ITrigger>>();
                   IJobDetail detail = new JobDetailImpl("job_" + count, schedId, typeof(SimpleRecoveryJob));
                   ITrigger simple = new SimpleTriggerImpl("trig_" + count, schedId, 20, TimeSpan.FromMilliseconds(4500));
                   var triggers = new Collection.HashSet<ITrigger>();
                   triggers.Add(simple);
                   info[detail] = triggers;

                   scheduler.ScheduleJobs(info, true);

                   Assert.IsTrue(scheduler.CheckExists(detail.Key));
                   Assert.IsTrue(scheduler.CheckExists(simple.Key));

                   // QRTZNET-243
                   scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupContains("a").DeepClone());
                   scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEndsWith("a").DeepClone());
                   scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupStartsWith("a").DeepClone());
                   scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals("a").DeepClone());

                   scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupContains("a").DeepClone());
                   scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEndsWith("a").DeepClone());
                   scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupStartsWith("a").DeepClone());
                   scheduler.GetTriggerKeys(GroupMatcher<TriggerKey>.GroupEquals("a").DeepClone());

                   scheduler.Start();

                   Thread.Sleep(TimeSpan.FromSeconds(3));

                   scheduler.PauseAll();

                   scheduler.ResumeAll();

                   scheduler.PauseJob(new JobKey("job_1", schedId));

                   scheduler.ResumeJob(new JobKey("job_1", schedId));

                   scheduler.PauseJobs(GroupMatcher<JobKey>.GroupEquals(schedId));

                   Thread.Sleep(TimeSpan.FromSeconds(1));

                   scheduler.ResumeJobs(GroupMatcher<JobKey>.GroupEquals(schedId));

                   scheduler.PauseTrigger(new TriggerKey("trig_2", schedId));
                   scheduler.ResumeTrigger(new TriggerKey("trig_2", schedId));

                   scheduler.PauseTriggers(GroupMatcher<TriggerKey>.GroupEquals(schedId));

                   Assert.AreEqual(1, scheduler.GetPausedTriggerGroups().Count);

                   Thread.Sleep(TimeSpan.FromSeconds(3));
                   scheduler.ResumeTriggers(GroupMatcher<TriggerKey>.GroupEquals(schedId));

                   Assert.IsNotNull(scheduler.GetTrigger(new TriggerKey("trig_2", schedId)));
                   Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_1", schedId)));
                   Assert.IsNotNull(scheduler.GetMetaData());
                   Assert.IsNotNull(scheduler.GetCalendar("weeklyCalendar"));

                   Thread.Sleep(TimeSpan.FromSeconds(20));

                   scheduler.Standby();

                   CollectionAssert.IsNotEmpty(scheduler.GetCalendarNames());
                   CollectionAssert.IsNotEmpty(scheduler.GetJobKeys(GroupMatcher<JobKey>.GroupEquals(schedId)));

                   CollectionAssert.IsNotEmpty(scheduler.GetTriggersOfJob(new JobKey("job_2", schedId)));
                   Assert.IsNotNull(scheduler.GetJobDetail(new JobKey("job_2", schedId)));

                   scheduler.DeleteCalendar("cronCalendar");
                   scheduler.DeleteCalendar("holidayCalendar");
                   scheduler.DeleteJob(new JobKey("lonelyJob", "lonelyGroup"));
                   scheduler.DeleteJob(job.Key);

                   scheduler.GetJobGroupNames();
                   scheduler.GetCalendarNames();
                   scheduler.GetTriggerGroupNames();
               }
               }
               finally
               {
               scheduler.Shutdown(false);
               }
        }
示例#36
0
        private void AddJob6(IScheduler scheduler, IJobDetail job, ISimpleTrigger trigger)
        {
            job = JobBuilder.Create<SimpleJob>()
                    .WithIdentity("job6", "group1")
                    .StoreDurably()
                    .Build();

            scheduler.AddJob(job, true);
            log.Info("'Manually triggering job6...");
            scheduler.TriggerJob(new JobKey("job6", "group1"));
        }