コード例 #1
0
            public TestContext ActScheduleFiniteRecurringJob()
            {
                _scheduler
                .Expect(s =>
                        s.ScheduleJob(
                            Arg <ITrigger> .Matches(t =>
                                                    Equals(t.Key, new TriggerKey(_scheduleId.ToString())) &&
                                                    Equals(t.JobKey, JobKey.Create(_jobId.ToString())) &&
                                                    t.Description == _description &&
                                                    Equals(t.StartTimeUtc, _startUtc) &&
                                                    t.JobDataMap.GetLong("CreatedUtc") == _now.Utc.Ticks &&
                                                    t.JobDataMap.GetString("Cron") == _cron &&
                                                    Equals(t.EndTimeUtc.Value, _endUtc))))
                .Return(_fixture.Create <DateTimeOffset>());

                _sut.Create(_scheduleId, _jobId, _description, _startUtc, _cron, _endUtc);

                return(this);
            }
コード例 #2
0
ファイル: RAMJobStoreTest.cs プロジェクト: zidanfei/quartznet
        public async Task testStoreAndRetrieveJobs()
        {
            RAMJobStore store = new RAMJobStore();

            // Store jobs.
            for (int i = 0; i < 10; i++)
            {
                IJobDetail job = JobBuilder.Create <NoOpJob>().WithIdentity("job" + i).Build();
                await store.StoreJob(job, false);
            }
            // Retrieve jobs.
            for (int i = 0; i < 10; i++)
            {
                JobKey     jobKey    = JobKey.Create("job" + i);
                IJobDetail storedJob = await store.RetrieveJob(jobKey);

                Assert.AreEqual(jobKey, storedJob.Key);
            }
        }
コード例 #3
0
        public async Task JobTypeNotFoundShouldNotBlock()
        {
            NameValueCollection properties = new NameValueCollection();

            properties.Add(StdSchedulerFactory.PropertySchedulerTypeLoadHelperType, typeof(SpecialClassLoadHelper).AssemblyQualifiedName);
            var scheduler = await CreateScheduler(properties);

            await scheduler.DeleteJobs(new[] { JobKey.Create("bad"), JobKey.Create("good") });

            await scheduler.Start();

            var manualResetEvent = new ManualResetEventSlim(false);

            scheduler.Context.Put(KeyResetEvent, manualResetEvent);

            IJobDetail goodJob = JobBuilder.Create <GoodJob>().WithIdentity("good").Build();
            IJobDetail badJob  = JobBuilder.Create <BadJob>().WithIdentity("bad").Build();

            var      now         = DateTimeOffset.UtcNow;
            ITrigger goodTrigger = TriggerBuilder.Create().WithIdentity("good").ForJob(goodJob)
                                   .StartAt(now.AddMilliseconds(1))
                                   .Build();

            ITrigger badTrigger = TriggerBuilder.Create().WithIdentity("bad").ForJob(badJob)
                                  .StartAt(now)
                                  .Build();

            var toSchedule = new Dictionary <IJobDetail, IReadOnlyCollection <ITrigger> >();

            toSchedule.Add(badJob, new List <ITrigger>
            {
                badTrigger
            });
            toSchedule.Add(goodJob, new List <ITrigger>
            {
                goodTrigger
            });
            await scheduler.ScheduleJobs(toSchedule, true);

            manualResetEvent.Wait(TimeSpan.FromSeconds(20));

            Assert.That(await scheduler.GetTriggerState(badTrigger.Key), Is.EqualTo(TriggerState.Error));
        }
コード例 #4
0
        public async Task <IActionResult> Save([FromForm] JobViewModel model, bool trigger)
        {
            var jobModel   = model.Job;
            var jobDataMap = (await Request.GetJobDataMapForm()).GetModel(Services);

            var result = new ValidationResult();

            model.Validate(result.Errors);
            ModelValidator.Validate(jobDataMap, result.Errors);

            if (result.Success)
            {
                IJobDetail BuildJob(JobBuilder builder)
                {
                    return(builder
                           .OfType(Type.GetType(jobModel.Type, true))
                           .WithIdentity(jobModel.JobName, jobModel.Group)
                           .WithDescription(jobModel.Description)
                           .SetJobData(jobDataMap.GetQuartzJobDataMap())
                           .RequestRecovery(jobModel.Recovery)
                           .Build());
                }

                if (jobModel.IsNew)
                {
                    await Scheduler.AddJob(BuildJob(JobBuilder.Create().StoreDurably()), replace : false);
                }
                else
                {
                    var oldJob = await GetJobDetail(JobKey.Create(jobModel.OldJobName, jobModel.OldGroup));

                    await Scheduler.UpdateJob(oldJob.Key, BuildJob(oldJob.GetJobBuilder()));
                }

                if (trigger)
                {
                    await Scheduler.TriggerJob(JobKey.Create(jobModel.JobName, jobModel.Group));
                }
            }

            return(Json(result));
        }
コード例 #5
0
        public IJobDetail CreateJob(EbTask _task)
        {
            JobKey     jobKey;
            IJobDetail job = null;

            JobDataMap _dataMap = new JobDataMap();

            _dataMap.Add("args", JsonConvert.SerializeObject(_task.JobArgs));

            jobKey = JobKey.Create(((JobTypes)_task.JobType).ToString() + DateTime.Now);

            if (_task.JobType == JobTypes.EmailTask)
            {
                job = JobBuilder.Create <EmailJob>().WithIdentity(jobKey).UsingJobData(_dataMap).Build();
            }
            else if (_task.JobType == JobTypes.SmsTask)
            {
                job = JobBuilder.Create <SmsJob>().WithIdentity(jobKey).UsingJobData(_dataMap).Build();
            }
            else if (_task.JobType == JobTypes.Slack)
            {
                job = JobBuilder.Create <SlackJob>().WithIdentity(jobKey).UsingJobData(_dataMap).Build();
            }
            else if (_task.JobType == JobTypes.ReportTask)
            {
                job = JobBuilder.Create <ReportJob>().WithIdentity(jobKey).UsingJobData(_dataMap).Build();
            }
            else if (_task.JobType == JobTypes.SqlJobTask)
            {
                job = JobBuilder.Create <SqlJob>().WithIdentity(jobKey).UsingJobData(_dataMap).Build();
            }
            else if (_task.JobType == JobTypes.ApiTask)
            {
                job = JobBuilder.Create <ApiJob>().WithIdentity(jobKey).UsingJobData(_dataMap).Build();
            }
            else if (_task.JobType == JobTypes.MyJob)
            {
                job = JobBuilder.Create <MyJob>().WithIdentity(jobKey).Build();
            }

            return(job);
        }
コード例 #6
0
        public JsonResult DeleteJob()
        {
            try
            {
                IScheduler scheduler = QuartzNetHelper.GetScheduler();
                if (!scheduler.IsStarted)
                {
                    scheduler.Start();
                }
                int             jobId     = Convert.ToInt32(Request["jobId"]);
                string          jobName   = Request["jobName"];
                CustomJobDetail customJob = CustomJobDetailBLL.CreateInstance().Get(jobId, jobName);
                scheduler.PauseTrigger(new TriggerKey(customJob.JobName, customJob.JobGroup));
                scheduler.UnscheduleJob(new TriggerKey(customJob.JobName, customJob.JobGroup));

                var jobKey = JobKey.Create(customJob.JobName, customJob.JobGroup);
                if (scheduler.CheckExists(jobKey))
                {
                    var result = scheduler.DeleteJob(jobKey);

                    if (result)
                    {
                        CustomJobDetailBLL.CreateInstance().Delete(customJob.JobId, customJob.JobName);
                    }

                    if (result)
                    {
                        return(Json(new { Code = 1, Message = "执行成功!" }));
                    }
                    else
                    {
                        return(Json(new { Code = 0, Message = "执行失败!" }));
                    }
                }
                return(Json(new { Code = 1, Message = "执行成功!" }));
            }
            catch (Exception ex)
            {
                Log4NetHelper.WriteExcepetion(ex);
                return(Json(new { Code = 0, Message = "执行失败!" }));
            }
        }
コード例 #7
0
        public async Task <IActionResult> Edit(string name, string group, bool clone = false)
        {
            if (!EnsureValidKey(name, group))
            {
                return(BadRequest());
            }

            var jobKey = JobKey.Create(name, group);
            var job    = await GetJobDetail(jobKey);

            var jobModel = new JobPropertiesViewModel()
            {
            };
            var jobDataMap = new JobDataMapModel()
            {
                Template = JobDataMapItemTemplate
            };

            jobModel.IsNew     = clone;
            jobModel.IsCopy    = clone;
            jobModel.JobName   = name;
            jobModel.Group     = group;
            jobModel.GroupList = (await Scheduler.GetJobGroupNames()).GroupArray();

            jobModel.Type     = job.JobType.RemoveAssemblyDetails();
            jobModel.TypeList = Services.Cache.JobTypes;

            jobModel.Description = job.Description;
            jobModel.Recovery    = job.RequestsRecovery;

            if (clone)
            {
                jobModel.JobName += " - Copy";
            }

            jobDataMap.Items.AddRange(job.GetJobDataMapModel(Services));

            return(View("Edit", new JobViewModel()
            {
                Job = jobModel, DataMap = jobDataMap
            }));
        }
コード例 #8
0
        public async Task <DateTime?> GetNextRunTime(int jobId)
        {
            JobKey jobKey   = JobKey.Create(jobId.ToString());
            var    triggers = await scheduler.GetTriggersOfJob(jobKey);

            if (triggers.Count != 1)
            {
                return(null);
            }

            var trigger      = triggers.FirstOrDefault();
            var triggerState = await scheduler.GetTriggerState(trigger.Key);

            if (triggerState == TriggerState.Paused)
            {
                return(null);
            }

            return(trigger.GetNextFireTimeUtc()?.LocalDateTime);
        }
コード例 #9
0
        public void testStoreAndRetrieveJobs()
        {
            InitJobStore();

            var store = new RavenJobStore();

            // Store jobs.
            for (int i = 0; i < 10; i++)
            {
                IJobDetail job = JobBuilder.Create <NoOpJob>().WithIdentity("job" + i).Build();
                store.StoreJob(job, false);
            }
            // Retrieve jobs.
            for (int i = 0; i < 10; i++)
            {
                JobKey     jobKey    = JobKey.Create("job" + i);
                IJobDetail storedJob = store.RetrieveJob(jobKey);
                Assert.AreEqual(jobKey, storedJob.Key);
            }
        }
コード例 #10
0
        public async Task <IActionResult> PostTrigger(string name, string group)
        {
            if (!EnsureValidKey(name, group))
            {
                return(BadRequest());
            }

            var jobDataMap = (await Request.GetJobDataMapForm()).GetModel(Services);

            var result = new ValidationResult();

            ModelValidator.Validate(jobDataMap, result.Errors);

            if (result.Success)
            {
                await Scheduler.TriggerJob(JobKey.Create(name, group), jobDataMap.GetQuartzJobDataMap());
            }

            return(Json(result));
        }
コード例 #11
0
ファイル: ExecuteAJob.cs プロジェクト: anthrax3/QuartzAdmin
        public void Execute_a_job_with_job_data_map()
        {
            // Arrange
            // - Add a job into the test scheduler
            IScheduler sched = GetTestScheduler();
            IJobDetail job   = JobBuilder.Create <NoOpJob>()
                               .WithIdentity("TestJob2", "TestGroup")
                               .UsingJobData("MyParam1", "Initial Data")
                               .Build();

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

            context.SetupGet(x => x.Request).Returns(request.Object);
            NameValueCollection formParameters = new NameValueCollection();

            formParameters.Add("jdm_MyParam1", "Working on the railroad");
            request.SetupGet(x => x.Form).Returns(formParameters);


            // - Create the fake instance repo and the job execution controller
            IInstanceRepository instanceRepo = new FakeInstanceRepository();

            instanceRepo.Save(GetTestInstance());
            JobExecutionController jec = new JobExecutionController(instanceRepo);

            // - Set the mocked context for the controller
            jec.ControllerContext = new ControllerContext(context.Object, new RouteData(), jec);

            // Act
            ActionResult result = jec.RunNow("MyTestInstance", "TestGroup", "TestJob2");
            // - Get the triggers of the job
            IList <ITrigger> trigOfJob = sched.GetTriggersOfJob(JobKey.Create("TestJob2", "TestGroup"));

            //Assert
            Assert.IsTrue(result is ContentResult && ((ContentResult)result).Content == "Job execution started");
            Assert.IsTrue(trigOfJob.Count() > 0);
            Assert.AreEqual(trigOfJob[0].JobDataMap["MyParam1"], "Working on the railroad");
        }
コード例 #12
0
        public async Task ScheduleJobAsync(string jobId, JobDataModel jobData)
        {
            if (!SchedulerClientConfig.Version.Equals(jobData.SdkVersion))
            {
                throw new ApiValidationException("Invalid SDK version");
            }

            invalidatedEvent.WaitOne();

            var jobKey = JobKey.Create(jobId);

            using (await jobLockProvider.AcquireAsync(jobKey))
            {
                if (await scheduler.CheckJobExistsAsync(jobKey))
                {
                    var existingJobDetail = await scheduler.GetJobDetailAsync(jobKey);

                    if (jobData.GetDataHashCode().Equals(existingJobDetail.GetDataHashCode()))
                    {
                        Log.Debug("{jobId} job is up to date", jobId);
                        return;
                    }

                    Log.Debug("{jobId} job will be updated", jobId);

                    await scheduler.DeleteJobAsync(jobKey);

                    Log.Information("{jobId} job was deleted", jobKey.Name);
                }

                var newJobDetail = JobDetailFactory.Create(jobKey, jobData);
                await scheduler.CreateJobAsync(newJobDetail);

                Log.Information("{jobId} job was created", jobId);

                var newTrigger      = TriggerFactory.Create(jobKey, jobData);
                var firstFireMoment = await scheduler.CreateTriggerAsync(newTrigger);

                Log.Information($"{{jobId}} job was scheduled (next execution: {firstFireMoment})", jobId);
            }
        }
コード例 #13
0
        public FileInfo GetExcel(jobextend jext)
        {
            var key       = JobKey.Create(jext.JobName, jext.JobGroup);
            var scheduler = GetScheduler();
            // нашли задачу
            var job = scheduler.GetJobDetail(key);

            var param = (Report)job.JobDataMap["param"];
            var jxml  = db.reportxml.Single(x => x.JobName == jext.JobName);

            // вытащили сохраненный отчет
            var ds = new DataSet();

            ds.ReadXml(new StringReader(jxml.Xml), XmlReadMode.ReadSchema);

            // создали процессор для этого типа отчетов
            var processor = param.GetProcessor();

            // создали excel-файл
            return(processor.CreateExcel(jext.JobGroup, jext.JobName, ds, param));
        }
コード例 #14
0
        public static bool removeJob(String jobName, String triggerName, String GroupName)
        {
            var scheduler  = new StdSchedulerFactory().GetScheduler().Result;
            var triggerKey = new TriggerKey(triggerName, GroupName);
            var jobKey     = JobKey.Create(jobName, GroupName);

            try
            {
                scheduler.PauseJob(jobKey);
                scheduler.PauseTrigger(triggerKey);                              // 停止触发器
                var unscheduledJob = scheduler.UnscheduleJob(triggerKey).Result; // 移除触发器
                var deleteJob      = scheduler.DeleteJob(jobKey).Result;         // 删除任务
                return(deleteJob || unscheduledJob);
            }
            catch (Exception e)
            {
                Logs.PrintLog(e);
                //  throw new RuntimeException(e);
            }
            return(false);
        }
コード例 #15
0
        public async Task <IActionResult> Trigger(string name, string group)
        {
            if (!EnsureValidKey(name, group))
            {
                return(BadRequest());
            }

            var jobKey = JobKey.Create(name, group);
            var job    = await GetJobDetail(jobKey);

            var jobDataMap = new JobDataMapModel {
                Template = JobDataMapItemTemplate
            };

            ViewBag.JobName = name;
            ViewBag.Group   = group;

            jobDataMap.Items.AddRange(job.GetJobDataMapModel(Services));

            return(View(jobDataMap));
        }
コード例 #16
0
        public async static Task CancelSchedulerJob(int jobId)
        {
            string prefix   = "processpendingfile";
            string JobName  = prefix + "Job_" + jobId;
            string JobGroup = prefix + "Group";
            var    jobKey   = JobKey.Create(JobName, JobGroup);

            //         string prefix = "processpendingfile";
            //           string JobName = prefix + "Job_" + jobId;
            //         string JobGroup = prefix + "Group";
            ISchedulerFactory schedFact = new StdSchedulerFactory();
            IScheduler        sched     = await schedFact.GetScheduler();

            //       var jobKey = JobKey.Create(JobName,JobGroup);
            var jobExist = await sched.CheckExists(jobKey);

            if (jobExist)
            {
                await sched.DeleteJob(jobKey);
            }
        }
コード例 #17
0
ファイル: IPCServer.cs プロジェクト: Yankyhyz/bit
        public void Stop(string name)
        {
            try
            {
                BitAdminService.Scheduler.DeleteJob(JobKey.Create(name));

                var stop = ConfigurationManager.AppSettings["Stop"].Split(',').ToList();
                if (!stop.Contains(name))
                {
                    stop.Add(name);
                    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                    config.AppSettings.Settings["Stop"].Value = string.Join(",", stop.ToArray());
                    config.Save(ConfigurationSaveMode.Modified);
                    ConfigurationManager.RefreshSection("appSettings");
                }
            }
            catch (Exception ex)
            {
                LogHelper.SaveLog(ex);
            }
        }
コード例 #18
0
        public ActionResult Backup()
        {
            var scheduler = IoC.Get <IScheduler>();

            scheduler.TriggerJob(JobKey.Create(CloudBackupJob.Identity));

            var details = scheduler.GetJobDetail(JobKey.Create(CloudBackupJob.Identity));

            var result = details.Description;

            if (result != null)
            {
                SuccessNotification(string.Format(Resources.Messages_BackupComplete, result));
            }
            else
            {
                ErrorNotification(Resources.Messages_BackupFailure);
            }

            return(RedirectToThen());
        }
コード例 #19
0
            private void ArrangeJob(HttpVerb httpVerb)
            {
                var jobId  = _context.JobDetail.Key.Name;
                var jobKey = JobKey.Create(jobId);

                _job =
                    new Job(
                        new Guid(jobId),
                        _fixture.Create <string>(),
                        _fixture.Create <Uri>(),
                        httpVerb,
                        _fixture.Create <string>(),
                        "application/json",
                        null,
                        _fixture.Create <DateTime>(),
                        _timeout);

                _converter
                .Expect(c => c.For(Arg <IJobDetail> .Matches(j => Equals(_context.JobDetail.Key, jobKey))))
                .Return(_job);
            }
コード例 #20
0
        private static async Task MainAsync()
        {
            var jobDetails = JobBuilder.Create <ProductsJob>()
                             .WithIdentity(JobKey.Create(ConfigurationModule.Scheduler.WebSiteProductsSyncJob_DisplayName, nameof(ProductsJob)))
                             .Build();

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(new TriggerKey(ConfigurationModule.Scheduler.WebSiteProductsSyncJob_TriggerName, nameof(ProductsJob)))
                          .StartNow()
                          .WithSimpleSchedule(builder =>
            {
                builder.WithIntervalInSeconds(ConfigurationModule.Scheduler.WebSiteProductsSyncJob_ExecutionTime)
                .RepeatForever();
            })
                          .Build();


            var scheduler = await new StdSchedulerFactory().GetScheduler();
            await scheduler.ScheduleJob(jobDetails, trigger);

            await scheduler.Start();
        }
コード例 #21
0
 public void StopJob(string jobId, bool success)
 {
     using (ILoggingOperation log = _logger.NormalOperation()
                                    .AddProperty("jobId", jobId))
     {
         log.Wrap(() =>
         {
             if (!Global.Scheduler.DeleteJob(JobKey.Create(jobId, ServiceConstants.JobGroupName)))
             {
                 throw new Exception("Error executing job deletion.");
             }
             if (success)
             {
                 log.Info($"job stopped with success");
             }
             else
             {
                 log.Info($"job stopped with failure");
             }
         });
     }
 }
コード例 #22
0
    public async Task CreateJobAsync(JobInfo jobInfo)
    {
        using var logScope = _logger.BeginScope(Context.ConnectionId);
        var scheduler = await _schedulerWorker.GetSchedulerAsync(SchedulerName);

        var jobKey    = JobKey.Create(jobInfo.JobKey);
        var jobDetail = await scheduler.GetJobDetail(jobKey);

        if (jobDetail == null)
        {
            var newJob = JobBuilder.Create <SignalRScheduleJob>()
                         .WithIdentity(jobKey)
                         .WithDescription(jobInfo.Description)
                         .UsingJobData(nameof(Context.ConnectionId), Context.ConnectionId)
                         .UsingJobData(nameof(jobInfo.MethodName), jobInfo.MethodName)
                         .Build();

            var trigger = TriggerBuilder.Create()
                          .ForJob(jobKey)
                          .WithCronSchedule(jobInfo.CronExpression)
                          .Build();

            await scheduler.ScheduleJob(newJob, trigger);

            if (Context.Items["JobKeys"] is ISet <JobKey> jobKeys)
            {
                jobKeys.Add(jobKey);
            }
            else
            {
                jobKeys = new HashSet <JobKey>();
                jobKeys.Add(jobKey);
                Context.Items["JobKeys"] = jobKeys;
            }
            _logger.LogInformation(1, "创建任务[{}]成功", jobKey);
            _logger.LogInformation(1, "调度策略:{}", jobInfo.CronExpression);
        }
    }
コード例 #23
0
 /// <summary>
 /// 添加任务
 /// </summary>
 /// <param name="jobConfig"></param>
 /// <returns></returns>
 public bool AddJob(JobConfig jobConfig)
 {
     try
     {
         var  currentScheduler = GetScheduler(jobConfig.SchedulerName);
         bool isHasJob         = currentScheduler.CheckExists(JobKey.Create(jobConfig.JobName, jobConfig.JobGroup)).Result;
         bool isHasTrigger     = currentScheduler.CheckExists(new TriggerKey(jobConfig.TriggerName, jobConfig.TriggerGroup)).Result;
         if (isHasTrigger && isHasJob)
         {
             return(false);
         }
         ITrigger trigger = TriggerBuilder.Create()
                            .WithIdentity(jobConfig.TriggerName, jobConfig.TriggerGroup)
                            .WithCronSchedule(jobConfig.CronExpression).Build();
         IJobDetail jobDetail = JobBuilder.Create(jobConfig.JobType).SetJobData(new JobDataMap(jobConfig.JobDataMap)).WithIdentity(jobConfig.JobName, jobConfig.JobGroup).Build();
         currentScheduler.ScheduleJob(jobDetail, trigger);
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
コード例 #24
0
            public TestContext ArrangeNeverEndingRecurringSchedule()
            {
                const string cron = "* * * ? * *";

                _trigger =
                    new CronTriggerImpl
                {
                    Key          = new TriggerKey(_scheduleId.ToString()),
                    JobKey       = JobKey.Create(_jobId.ToString()),
                    Description  = _description,
                    StartTimeUtc = _startUtc,
                    JobDataMap   =
                        new JobDataMap
                    {
                        { "CreatedUtc", _createdUtc.Ticks },
                        { "Cron", cron }
                    },
                    CronExpressionString = cron
                };
                _expected
                .WithCron(cron);
                return(this);
            }
コード例 #25
0
        public void OnStart()
        {
            var schedulerFactory = new StdSchedulerFactory();
            var scheduler        = schedulerFactory.GetScheduler().Result;

            scheduler.JobFactory = _jobFactory;
            scheduler.Start().Wait();

            var jobDetails = JobBuilder.Create <SampleJob>()
                             .WithIdentity(JobKey.Create("Name of the service", "Group of the service"))
                             .Build();

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(new TriggerKey("Name of the service", "Group of the service"))
                          .StartNow()
                          .WithSimpleSchedule(builder =>
            {
                builder.WithIntervalInSeconds(120).RepeatForever();
            })
                          .Build();

            scheduler.ScheduleJob(jobDetails, trigger).Wait();
        }
コード例 #26
0
ファイル: Scheduler.cs プロジェクト: Growth-Tools/WebHawk
        public void RemoveTask(ScheduledTask task)
        {
            IJobListener jobListener = m_QuartzScheduler.ListenerManager.GetJobListener(task.TaskName);

            if (jobListener != null)
            {
                //Following should always be true, but checking anyway in case the use of jobs is expanded
                if (jobListener is ExecuteSequenceJobListener)
                {
                    ExecuteSequenceJobListener executeSequenceJobListener = (ExecuteSequenceJobListener)jobListener;
                    executeSequenceJobListener.TaskStart    -= jobListener_TaskStart;
                    executeSequenceJobListener.TaskComplete -= jobListener_TaskComplete;
                }
                m_QuartzScheduler.ListenerManager.RemoveJobListener(task.TaskName);
            }

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

            if (m_QuartzScheduler.CheckExists(jobKey))
            {
                m_QuartzScheduler.DeleteJob(jobKey);
            }
        }
コード例 #27
0
        public async Task TestStoreAndRetrieveTriggers()
        {
            var store = new RavenJobStore
            {
                Database = "QuartzTest",
                Urls     = "[\"http://localhost:8080\"]"
            };
            await store.Initialize(null, fSignaler);

            await store.SchedulerStarted();

            // Store jobs and triggers.
            for (var i = 0; i < 10; i++)
            {
                var job = JobBuilder.Create <NoOpJob>().WithIdentity("job" + i).Build();
                await store.StoreJob(job, true);

                var schedule = SimpleScheduleBuilder.Create();
                var trigger  = TriggerBuilder.Create().WithIdentity("trigger" + i).WithSchedule(schedule).ForJob(job)
                               .Build();
                await store.StoreTrigger((IOperableTrigger)trigger, true);
            }

            // Retrieve job and trigger.
            for (var i = 0; i < 10; i++)
            {
                var jobKey    = JobKey.Create("job" + i);
                var storedJob = await store.RetrieveJob(jobKey);

                Assert.AreEqual(jobKey, storedJob.Key);

                var      triggerKey    = new TriggerKey("trigger" + i);
                ITrigger storedTrigger = await store.RetrieveTrigger(triggerKey);

                Assert.AreEqual(triggerKey, storedTrigger.Key);
            }
        }
コード例 #28
0
ファイル: Program.cs プロジェクト: jmkasun/QuartzRemainder
        public static async Task TestDemoJob1(List <JobsAndTriggers> lstJobsAndTriggers)
        {
            IScheduler scheduler;
            IJobDetail job     = null;
            ITrigger   trigger = null;

            var schedulerFactory = new StdSchedulerFactory(ConfigurationManager.GetSection("quartz") as NameValueCollection);

            scheduler = schedulerFactory.GetScheduler().Result;
            scheduler.Start().Wait();

            foreach (var JobandTrigger in lstJobsAndTriggers)
            {
                JobKey jobKey = JobKey.Create(JobandTrigger.jobIdentityKey);

                job = JobBuilder.Create <DemoJob1>().
                      WithIdentity(jobKey)
                      .UsingJobData("MethodName", JobandTrigger.jobData_MethodName)
                      .Build();

                //trigger = TriggerBuilder.Create()
                //.WithIdentity(JobandTrigger.TriggerIdentityKey)
                //.StartNow()
                //.WithSimpleSchedule(x => x.WithIntervalInSeconds(JobandTrigger.ScheduleIntervalInSec).WithRepeatCount(1)
                ////.RepeatForever()
                //)
                //.Build();

                trigger = (ISimpleTrigger)TriggerBuilder.Create()
                          .WithIdentity(JobandTrigger.TriggerIdentityKey)
                          .StartAt(DateBuilder.FutureDate(JobandTrigger.ScheduleIntervalInSec, IntervalUnit.Second)) // use DateBuilder to create a date in the future
                          .ForJob(jobKey)                                                                            // identify job with its JobKey
                          .Build();

                await scheduler.ScheduleJob(job, trigger);
            }
        }
コード例 #29
0
        public async Task CreateOrUpdate(int jobId, string cronSchedule)
        {
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity(jobId.ToString())
                               .WithCronSchedule(cronSchedule)
                               .ForJob(jobId.ToString())
                               .Build();

            JobKey jobKey = JobKey.Create(jobId.ToString());
            IEnumerable <ITrigger> triggers = await scheduler.GetTriggersOfJob(jobKey);

            if (triggers != null && triggers.Count() == 1)
            {
                await scheduler.RescheduleJob(triggers.First().Key, trigger);
            }
            else
            {
                IJobDetail jobDetail = JobBuilder.Create <DefaultScheduledJob>()
                                       .WithIdentity(jobId.ToString())
                                       .Build();

                await scheduler.ScheduleJob(jobDetail, trigger);
            }
        }
コード例 #30
0
ファイル: Program.cs プロジェクト: drajend/IVR
        /// <summary>
        /// Scheduling Task for a specific interval
        /// </summary>
        /// <returns></returns>
        public static async Task TaskIVRJob()
        {
            try
            {
                Log.Information($"[{ DateTime.Now}]  TaskIVRJob Task Method started!");

                IScheduler scheduler;

                var schedulerFactory = new StdSchedulerFactory();

                scheduler = schedulerFactory.GetScheduler().Result;

                scheduler.Start().Wait();
                // dynamic builder;
                Configurationsettings();

                int        ScheduleIntervalInMinute = Convert.ToInt32(Configuration["ScheduleIntervalInMinute"]);
                JobKey     jobKey  = JobKey.Create("IVRJob");
                IJobDetail job     = JobBuilder.Create <IVRJob>().WithIdentity(jobKey).Build();
                ITrigger   trigger = TriggerBuilder.Create()
                                     .WithIdentity("JobTrigger")
                                     .StartNow()
                                     .WithSimpleSchedule(x => x.WithIntervalInMinutes(ScheduleIntervalInMinute).RepeatForever())
                                     .Build();
                await scheduler.ScheduleJob(job, trigger);

                Log.Information($"[{ DateTime.Now}]  TaskIVRJob Task Method ended!");
            }
            catch (System.Exception ex)
            {
                Log.Error("Error in main method" + ex.Message);
            }
            finally
            {
            }
        }