public void SetUp() { var cb = new ContainerBuilder(); cb.RegisterType<SampleJob>(); _container = cb.Build(); _factory = new StdSchedulerFactory(); _scheduler = _factory.GetScheduler(); _scheduler.JobFactory = new AutofacJobFactory(_container.Resolve<ILifetimeScope>(), QuartzAutofacFactoryModule.LifetimeScopeName); }
public void ServiceRegistration(IDexterContainer container) { container.Register<IJobFactory, DexterJobFactory>(LifeCycle.Singleton); StdSchedulerFactory stdSchedulerFactory = new StdSchedulerFactory(); IScheduler scheduler = stdSchedulerFactory.GetScheduler(); scheduler.JobFactory = container.Resolve<IJobFactory>(); container.Register(typeof(ISchedulerFactory), stdSchedulerFactory, LifeCycle.Singleton); container.Register(typeof(IScheduler), scheduler, LifeCycle.Singleton); }
public void SetUp() { var cb = new ContainerBuilder(); cb.RegisterType<SampleJob>(); cb.RegisterType<DisposableDependency>().InstancePerLifetimeScope(); _container = cb.Build(); _factory = new StdSchedulerFactory(); _scheduler = _factory.GetScheduler(); _lifetimeScope = _container.Resolve<ILifetimeScope>(); _jobFactory = new AutofacJobFactory(_lifetimeScope, QuartzAutofacFactoryModule.LifetimeScopeName); _scheduler.JobFactory = _jobFactory; }
private static IScheduler RunProgramRunExample(ILoggerFactory loggerFact) { var log = loggerFact.CreateLogger <Program>(); try { var config = Host.Services.GetService <IConfiguration>(); // Grab the Scheduler instance from the Factory NameValueCollection properties = new NameValueCollection { ["quartz.scheduler.instanceName"] = QuartzOpt.InstanceName, ["quartz.scheduler.instanceId"] = QuartzOpt.InsatanceId, ["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz", ["quartz.threadPool.threadCount"] = "5", ["quartz.jobStore.misfireThreshold"] = "60000", ["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz", ["quartz.jobStore.useProperties"] = "false", ["quartz.jobStore.dataSource"] = "default", ["quartz.jobStore.tablePrefix"] = "QRTZ_", ["quartz.jobStore.clustered"] = "true", ["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.MySQLDelegate, Quartz", ["quartz.dataSource.default.connectionString"] = config.GetConnectionString("QuatrzClustDatabase"), ["quartz.dataSource.default.provider"] = "MySql", ["quartz.serializer.type"] = "json", ["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz", ["quartz.scheduler.exporter.port"] = "555", ["quartz.scheduler.exporter.bindName"] = "QuartzScheduler", ["quartz.scheduler.exporter.channelType"] = "tcp", ["quartz.scheduler.exporter.channelName"] = "httpQuartz", ["quartz.scheduler.exporter.rejectRemoteRequests"] = "true" }; StdSchedulerFactory factory = new StdSchedulerFactory(properties); IScheduler scheduler = factory.GetScheduler().GetAwaiter().GetResult(); string machine = Environment.MachineName; QuartzDbContext db = Host.Services.GetService <QuartzDbContext>(); var listQuartzTask = db.QuartzTask.Where(w => w.IsDelete == 0 && w.MachineName == machine && w.InstanceId == QuartzOpt.InsatanceId) .ToListAsync().GetAwaiter().GetResult(); log.LogDebug("从数据库获取task记录,详细信息:{0}", Newtonsoft.Json.JsonConvert.SerializeObject(listQuartzTask)); Dictionary <string, Assembly> collAssembly = new Dictionary <string, Assembly>(); foreach (var item in listQuartzTask) { //加载程序集 if (!string.IsNullOrEmpty(item.AssemblyName) && !collAssembly.ContainsKey(item.AssemblyName)) { try { collAssembly[item.AssemblyName] = AssemblyHelp.GetAssemblyByteByAssemblyName( Path.Combine(Directory.GetCurrentDirectory(), "AssemblyColl"), item.AssemblyName); } catch (Exception ep) { log.Log(Microsoft.Extensions.Logging.LogLevel.Error, 0, ep, "没有找到程序集."); Task.Delay(10000); continue; } } } // and start it off scheduler.Start(); // if (!QuartzOpt.IsSlave) // { var task = Task.Run(() => { bool isClear = QuartzOpt.IsClear; log.LogInformation("job监控程序开始循环,间隔为15秒"); while (true) { try { if (scheduler != null) { log.LogDebug("检查scheduler是否开始"); if (scheduler.IsStarted) { if (isClear) { scheduler.Clear().GetAwaiter().GetResult(); isClear = false; } log.LogDebug("scheduler已经开始"); db = Host.Services.GetService <QuartzDbContext>(); listQuartzTask = db.QuartzTask.Where(w => w.IsDelete == 0 && w.MachineName == machine && w.InstanceId == QuartzOpt.InsatanceId) .ToListAsync().GetAwaiter().GetResult(); log.LogDebug("从数据库获取task记录,详细信息:{0}", Newtonsoft.Json.JsonConvert.SerializeObject(listQuartzTask)); foreach (var item in listQuartzTask) { //加载程序集 if (!string.IsNullOrEmpty(item.AssemblyName) && !collAssembly.ContainsKey(item.AssemblyName)) { try { collAssembly[item.AssemblyName] = AssemblyHelp.GetAssemblyByteByAssemblyName( Path.Combine(Directory.GetCurrentDirectory(), "AssemblyColl"), item.AssemblyName); } catch (Exception ep) { log.Log(Microsoft.Extensions.Logging.LogLevel.Error, 0, ep, "没有找到程序集."); Task.Delay(10000); continue; } } log.LogDebug("开始检查task:{0}", Newtonsoft.Json.JsonConvert.SerializeObject(item)); var jobKey = new JobKey(item.TaskName, item.GroupName); var triggerKey = new TriggerKey(item.TaskName, item.GroupName); if (scheduler.CheckExists(jobKey).Result) { var jobDetai = scheduler.GetJobDetail(jobKey); var trigger = scheduler.GetTrigger(triggerKey); log.LogDebug("此task已经存在scheduler中,数据库状态:{0},scheduer中的状态:{1}.trigger状态:{2}" , ((OperateStatus)item.OperateStatus).ToString(), jobDetai.Status.ToString(), trigger.Status.ToString()); if ((OperateStatus)item.OperateStatus == OperateStatus.Stop) { log.LogInformation("删除schduler中的job:{0}", jobKey.ToString()); if (!scheduler.DeleteJob(jobKey).GetAwaiter().GetResult()) { log.LogError("删除job失败。name:{0},group:{1}", jobKey.Name, jobKey.Group); } } else { if (jobDetai.IsFaulted) { if (jobDetai.Exception != null) { log.LogError(10005, jobDetai.Exception, "job faulted"); } var jobItem = db.QuartzTask.FirstOrDefault(w => w.IsDelete == 0 && w.TaskName == jobKey.Name && w.GroupName == jobKey.Group && w.MachineName == machine && w.InstanceId == scheduler.SchedulerInstanceId); item.Status = (int)TaskStatus.Faulted; item.OperateStatus = (int)OperateStatus.Stop; db.Update <QuartzTask>(jobItem); db.SaveChanges(); } else { if (jobDetai.Status != TaskStatus.Running && jobDetai.Status != TaskStatus.RanToCompletion && jobDetai.Status != TaskStatus.WaitingForActivation && jobDetai.Status != TaskStatus.WaitingForChildrenToComplete && jobDetai.Status != TaskStatus.WaitingToRun) { var interTask = scheduler.Interrupt(jobKey, new CancellationToken(true)) .GetAwaiter().GetResult(); jobDetai.Start(); } } } var triggerListener = scheduler.ListenerManager.GetTriggerListener("triggerUpdate"); if (triggerListener == null) { triggerListener = new TriggerUpdateListens("trigger" + item.TaskName); IMatcher <TriggerKey> triggermatcher = KeyMatcher <TriggerKey> .KeyEquals(triggerKey); scheduler.ListenerManager.AddTriggerListener(triggerListener, triggermatcher); } var jobListener = scheduler.ListenerManager.GetJobListener("jobupdateListens"); if (jobListener == null) { IJobListener jobUpdateListener = new JobUpdateListens("job" + item.TaskName); IMatcher <JobKey> jobmatcher = KeyMatcher <JobKey> .KeyEquals(jobKey); scheduler.ListenerManager.AddJobListener(jobUpdateListener, jobmatcher); } } else { log.LogInformation("添加新的job,判断是否状态为停止。"); if ((OperateStatus)item.OperateStatus != OperateStatus.Stop) { log.LogInformation("添加新的job"); var assemblyName = item.AssemblyName; var className = item.ClassName; Type jobTaskType = null; try { jobTaskType = AssemblyHelp.GetTypeByAssemblyNameAndClassName(collAssembly[item.AssemblyName], className); log.LogInformation("找到类型,type:{0}", className); } catch (Exception ep) { log.Log(Microsoft.Extensions.Logging.LogLevel.Error, 0, ep, "没有找到type."); } if (jobTaskType == null) { try { jobTaskType = AssemblyHelp .GetTypeByCurrentAssemblyNameAndClassName(className, Assembly.GetExecutingAssembly()); if (jobTaskType == null) { log.LogInformation("没有找到类型"); continue; } log.LogInformation("找到类型,type:{0}", className); } catch (Exception ep) { log.Log(Microsoft.Extensions.Logging.LogLevel.Error, 0, ep, "没有找到类型."); continue; } } IJobDetail job = JobBuilder.Create(jobTaskType) .WithIdentity(item.TaskName, item.GroupName) .Build(); ITrigger trigger = TriggerBuilder.Create() .WithIdentity(item.TaskName, item.GroupName) .StartNow() .WithCronSchedule(item.CronExpressionString) .Build(); scheduler.ScheduleJob(job, trigger).GetAwaiter().GetResult(); log.LogInformation("添加成功,type:{0}", className); ITriggerListener triggerListener = new TriggerUpdateListens("trigger" + item.TaskName); IMatcher <TriggerKey> triggermatcher = KeyMatcher <TriggerKey> .KeyEquals(trigger.Key); scheduler.ListenerManager.AddTriggerListener(triggerListener, triggermatcher); IJobListener jobUpdateListener = new JobUpdateListens("job" + item.TaskName); IMatcher <JobKey> jobmatcher = KeyMatcher <JobKey> .KeyEquals(job.Key); scheduler.ListenerManager.AddJobListener(jobUpdateListener, jobmatcher); } } } } else { log.LogInformation("scheduler is not IsStarted"); } } else { log.LogInformation("scheduler is null"); } } catch (Exception ep) { log.Log(Microsoft.Extensions.Logging.LogLevel.Error, 0, ep, "task监控程序执行错误."); } Thread.Sleep(15000); } }); // } // else // { // db = Host.Services.GetService<QuartzDbContext>(); // listQuartzTask = db.QuartzTask.Where(w => w.IsDelete == 0 // && w.MachineName == machine // && w.InstanceId == QuartzOpt.InsatanceId) // .ToListAsync().GetAwaiter().GetResult(); // foreach (var item in listQuartzTask) // { // var jobKey = new JobKey(item.TaskName, item.GroupName); // var triggerKey = new TriggerKey(item.TaskName, item.GroupName); // // var jobItem = db.QuartzTask.FirstOrDefault(w => w.IsDelete == 0 // // && w.TaskName == jobKey.Name // // && w.GroupName == jobKey.Group // // && w.MachineName == machine // // && w.InstanceId == scheduler.SchedulerInstanceId); // // item.Status = (int)TaskStatus.Faulted; // // item.OperateStatus = (int)OperateStatus.Stop; // // db.Update<QuartzTask>(jobItem); // // db.SaveChanges(); // if (scheduler.CheckExists(jobKey).Result) // { // var triggerListener = scheduler.ListenerManager.GetTriggerListener("triggerUpdate"); // if (triggerListener == null) // { // triggerListener = new TriggerUpdateListens(); // IMatcher<TriggerKey> triggermatcher = KeyMatcher<TriggerKey>.KeyEquals(triggerKey); // scheduler.ListenerManager.AddTriggerListener(triggerListener, triggermatcher); // } // var jobListener = scheduler.ListenerManager.GetJobListener("jobupdateListens"); // if (jobListener == null) // { // IJobListener jobUpdateListener = new JobUpdateListens(); // IMatcher<JobKey> jobmatcher = KeyMatcher<JobKey>.KeyEquals(jobKey); // scheduler.ListenerManager.AddJobListener(jobUpdateListener, jobmatcher); // } // } // } //} return(scheduler); // Tell quartz to schedule the job using our trigger //await scheduler.ScheduleJob(job, trigger); } catch (SchedulerException sep) { log.Log(Microsoft.Extensions.Logging.LogLevel.Error, 0, sep, "job执行错误。"); } return(null); }
public static void Start() { var scheduler = StdSchedulerFactory.GetDefaultScheduler(); scheduler.Start(); }
public static void StartAsync() { bool jobExecStatus = false; string schlogMessage = ""; try { //IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler(); log.Info("Scheduler instance invoked."); ISchedulerFactory schedulerFactory = new StdSchedulerFactory(); IScheduler scheduler = schedulerFactory.GetScheduler(); IJobDetail job = JobBuilder.Create <SchedulerJob>().Build(); log.Info("Job instance created"); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("CEExtractorJob", "CEJOB") //"0 30 10 - 13 ? *WED,FRI" //"0 0 11 ? *MON" //.WithCronSche1dule("0 20 * 1/1 * ? *") //every 15 minutes //.WithCronSchedule("0 0/50 * * * ?") //every mon @ 1 PM IST Run the job and extract Comment Extractor Details .WithCronSchedule("0 0 13 ? * MON") //.StartAt(DateTime.UtcNow) .StartNow() .WithPriority(1) .Build(); log.Info("Job Trigger created"); scheduler.ScheduleJob(job, trigger); schedulerJobMessage = "Comment Extraction Scheduled to run @ " + TodDateUtils.GetCurrentTimeInIST(); log.Info("Scheduler scheduled instantiation successfully"); //register to listeners // add scheduler listener //scheduler.ListenerManager.AddSchedulerListener(); TodSchedulerJobListener todjoblistener = new TodSchedulerJobListener("CESchJobListener"); JobKey jk = new JobKey("CEExtractorJob", "CEJOB"); // add global job listener scheduler.ListenerManager.AddJobListener(todjoblistener, GroupMatcher <JobKey> .AnyGroup()); // add global trigger listener // scheduler.ListenerManager.AddTriggerListener(new GlobalTriggerListener(), GroupMatcher<TriggerKey>.AnyGroup()); //sched.ListenerManager.AddJobListener(todjoblistener, KeyMatcher<JobKey>.KeyEquals(jk)); log.Info("Scheduler registered successfully for job listener"); schlogMessage = "Scheduler scheduled successfully @ " + TodDateUtils.GetCurrentTimeInIST(); scheduler.Start(); log.Info("scheduler instance created and started"); jobExecStatus = true; } catch (Exception e) { log.Debug("Exception Occured. Detailed Exception is : "); log.Debug("--------"); log.Debug(e.Message); log.Debug("---------"); log.Debug("Stacktrace of the error is : \n" + e.StackTrace); schlogMessage = "Comment Extraction scheduled for " + DateTime.Now + " failed. Please check with Administrator for more details."; jobExecStatus = false; } //save the execution status with message to database scheduler log. try { using (var ctx = new TODEntities()) { TOD_TransactionLog todlog = new TOD_TransactionLog(); todlog.logtype = "CESCHLOG"; todlog.logdate = DateTime.Now.Date.ToString(); todlog.logMessage = schlogMessage; todlog.logStatus = jobExecStatus.ToString(); ctx.TOD_TransactionLog.Add(todlog); ctx.SaveChanges(); } } catch (Exception e) { log.Debug("Exception Occured. Detailed Exception is : "); log.Debug("--------"); log.Debug(e.Message); log.Debug("---------"); log.Debug("Stacktrace of the error is : \n" + e.StackTrace); schlogMessage = "Database Connection lazy initialization failed. Please check with administrator for more details."; jobExecStatus = false; } }
public virtual void Run() { ILog log = LogManager.GetLogger(typeof(CronTriggerExample)); log.Info("------- Initializing -------------------"); // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler sched = sf.GetScheduler(); log.Info("------- Initialization Complete --------"); log.Info("------- Scheduling Jobs ----------------"); // jobs can be scheduled before sched.start() has been called // job 1 will run every 20 seconds JobDetail job = new JobDetail("job1", "group1", typeof(SimpleJob)); CronTrigger trigger = new CronTrigger("trigger1", "group1", "job1", "group1", "0/20 * * * * ?"); sched.AddJob(job, true); DateTime ft = sched.ScheduleJob(trigger); #if !NET_35 ft = trigger.TimeZone.ToLocalTime(ft); #else ft = TimeZoneInfo.ConvertTimeFromUtc(ft, trigger.TimeZone); #endif log.Info(string.Format("{0} has been scheduled to run at: {1} and repeat based on expression: {2}", job.FullName, ft.ToString("r"), trigger.CronExpressionString)); // job 2 will run every other minute (at 15 seconds past the minute) job = new JobDetail("job2", "group1", typeof(SimpleJob)); trigger = new CronTrigger("trigger2", "group1", "job2", "group1", "15 0/2 * * * ?"); sched.AddJob(job, true); ft = sched.ScheduleJob(trigger); #if !NET_35 ft = trigger.TimeZone.ToLocalTime(ft); #else ft = TimeZoneInfo.ConvertTimeFromUtc(ft, trigger.TimeZone); #endif log.Info(string.Format("{0} has been scheduled to run at: {1} and repeat based on expression: {2}", job.FullName, ft.ToString("r"), trigger.CronExpressionString)); // job 3 will run every other minute but only between 8am and 5pm job = new JobDetail("job3", "group1", typeof(SimpleJob)); trigger = new CronTrigger("trigger3", "group1", "job3", "group1", "0 0/2 8-17 * * ?"); sched.AddJob(job, true); ft = sched.ScheduleJob(trigger); #if !NET_35 ft = trigger.TimeZone.ToLocalTime(ft); #else ft = TimeZoneInfo.ConvertTimeFromUtc(ft, trigger.TimeZone); #endif log.Info(string.Format("{0} has been scheduled to run at: {1} and repeat based on expression: {2}", job.FullName, ft.ToString("r"), trigger.CronExpressionString)); // job 4 will run every three minutes but only between 5pm and 11pm job = new JobDetail("job4", "group1", typeof(SimpleJob)); trigger = new CronTrigger("trigger4", "group1", "job4", "group1", "0 0/3 17-23 * * ?"); sched.AddJob(job, true); ft = sched.ScheduleJob(trigger); #if !NET_35 ft = trigger.TimeZone.ToLocalTime(ft); #else ft = TimeZoneInfo.ConvertTimeFromUtc(ft, trigger.TimeZone); #endif log.Info(string.Format("{0} has been scheduled to run at: {1} and repeat based on expression: {2}", job.FullName, ft.ToString("r"), trigger.CronExpressionString)); // job 5 will run at 10am on the 1st and 15th days of the month job = new JobDetail("job5", "group1", typeof(SimpleJob)); trigger = new CronTrigger("trigger5", "group1", "job5", "group1", "0 0 10am 1,15 * ?"); sched.AddJob(job, true); ft = sched.ScheduleJob(trigger); #if !NET_35 ft = trigger.TimeZone.ToLocalTime(ft); #else ft = TimeZoneInfo.ConvertTimeFromUtc(ft, trigger.TimeZone); #endif log.Info(string.Format("{0} has been scheduled to run at: {1} and repeat based on expression: {2}", job.FullName, ft.ToString("r"), trigger.CronExpressionString)); // job 6 will run every 30 seconds but only on Weekdays (Monday through // Friday) job = new JobDetail("job6", "group1", typeof(SimpleJob)); trigger = new CronTrigger("trigger6", "group1", "job6", "group1", "0,30 * * ? * MON-FRI"); sched.AddJob(job, true); ft = sched.ScheduleJob(trigger); #if !NET_35 ft = trigger.TimeZone.ToLocalTime(ft); #else ft = TimeZoneInfo.ConvertTimeFromUtc(ft, trigger.TimeZone); #endif log.Info(string.Format("{0} has been scheduled to run at: {1} and repeat based on expression: {2}", job.FullName, ft.ToString("r"), trigger.CronExpressionString)); // job 7 will run every 30 seconds but only on Weekends (Saturday and // Sunday) job = new JobDetail("job7", "group1", typeof(SimpleJob)); trigger = new CronTrigger("trigger7", "group1", "job7", "group1", "0,30 * * ? * SAT,SUN"); sched.AddJob(job, true); ft = sched.ScheduleJob(trigger); #if !NET_35 ft = trigger.TimeZone.ToLocalTime(ft); #else ft = TimeZoneInfo.ConvertTimeFromUtc(ft, trigger.TimeZone); #endif log.Info(string.Format("{0} has been scheduled to run at: {1} and repeat based on expression: {2}", job.FullName, ft.ToString("r"), trigger.CronExpressionString)); log.Info("------- Starting Scheduler ----------------"); // All of the jobs have been added to the scheduler, but none of the // jobs // will run until the scheduler has been started sched.Start(); log.Info("------- Started Scheduler -----------------"); log.Info("------- Waiting five minutes... ------------"); try { // wait five minutes to show jobs Thread.Sleep(300 * 1000); // executing... } catch (ThreadInterruptedException) { } log.Info("------- Shutting Down ---------------------"); sched.Shutdown(true); log.Info("------- Shutdown Complete -----------------"); SchedulerMetaData metaData = sched.GetMetaData(); log.Info(string.Format("Executed {0} jobs.", metaData.NumJobsExecuted)); }
/// <summary> /// Finalizes the configuration and builds the actual scheduler. /// </summary> public Task <IScheduler> Build() { var schedulerFactory = new StdSchedulerFactory(Properties); return(schedulerFactory.GetScheduler()); }
public static void Start() { log.Info("Starting scheduler"); var properties = new NameValueCollection(); // set remoting expoter properties["quartz.scheduler.exporter.type"] = ConfigurationManager.AppSettings["QuartzType"]; properties["quartz.scheduler.exporter.port"] = ConfigurationManager.AppSettings["QuartzPort"]; properties["quartz.scheduler.exporter.bindName"] = ConfigurationManager.AppSettings["QuartzBindName"]; properties["quartz.scheduler.exporter.channelType"] = ConfigurationManager.AppSettings["QuartzChannelType"]; properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; properties["quartz.threadPool.threadCount"] = "50"; properties["quartz.threadPool.threadPriority"] = "Normal"; ISchedulerFactory factory = new StdSchedulerFactory(properties); // get a scheduler _scheduler = factory.GetScheduler(); _config = (ConcentratorConfiguration)ConfigurationManager.GetSection("ConcentratorConfiguration"); #region System Plugins // Read the plugin path for available dll's _config.ScanPlugins(); foreach (Plugin plugin in _config.Plugins) { log.InfoFormat("Plugin found : {0}", plugin.Name); log.DebugFormat("Using typename : {0}", plugin.TypeName); plugin.Configure(); JobDetail jobDetail = CreateJob(plugin); _scheduler.AddJob(jobDetail, true); if (!String.IsNullOrEmpty(plugin.CronExpressionString)) { CronTrigger trigger = new CronTrigger(plugin.Name + " Trigger", plugin.Group, plugin.Name, plugin.Group, plugin.CronExpressionString); trigger.StartTimeUtc = DateTime.Now.ToUniversalTime(); _scheduler.ScheduleJob(trigger); } if (plugin.ExecuteOnStartUp) { //manually trigger this job per config settings _scheduler.TriggerJob(jobDetail.Name, jobDetail.Group); } } #endregion _scheduler.Start(); _running = true; log.DebugFormat(String.Format("{0} {1}", "Plugin".PadRight(30), "Next Execution Time".PadRight(25))); log.DebugFormat(new String('-', 60)); foreach (Plugin plugin in _config.Plugins) { Trigger[] triggers = _scheduler.GetTriggersOfJob(plugin.Name, plugin.Group); foreach (Trigger t in triggers) { if (t.Name.StartsWith("MT_")) // skip manual triggers in listing { continue; } log.DebugFormat("{0} {1}", plugin.Name.PadRight(30), (t.GetNextFireTimeUtc().ToString() ?? String.Empty).PadRight(25)); } } log.DebugFormat(new String('-', 60)); _monitor = new Thread(TimerThread); _monitor.Start(); //#if !DEBUG // if (ConfigurationManager.AppSettings["PluginListener"] != null) // { // string uri = string.Format("net.tcp://{0}:{1}/MiddleWareService", Dns.GetHostName(), int.Parse(ConfigurationManager.AppSettings["PluginListener"])); // _host = new ServiceHost(Instance, new Uri(uri)); // _host.AddServiceEndpoint(typeof(IConcentratorService), // new NetTcpBinding(), // new Uri(uri)); // _host.Open(); // } //#endif }
public Service() { StdSchedulerFactory factory = new StdSchedulerFactory(); scheduler = factory.GetScheduler().GetAwaiter().GetResult(); }
public virtual async Task Run() { ILog log = LogProvider.GetLogger(typeof(SchedulingJobsSettingMisfireInstructionsExample)); log.Info("------- Initializing -------------------"); // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler sched = await sf.GetScheduler(); log.Info("------- Initialization Complete -----------"); log.Info("------- Scheduling Jobs -----------"); // jobs can be scheduled before start() has been called // get a "nice round" time a few seconds in the future... DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 15); // statefulJob1 will run every three seconds // (but it will delay for ten seconds) IJobDetail job = JobBuilder.Create <StatefulDumbJob>() .WithIdentity("statefulJob1", "group1") .UsingJobData(StatefulDumbJob.ExecutionDelay, 10000L) .Build(); ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithIntervalInSeconds(3).RepeatForever()) .Build(); DateTimeOffset ft = await sched.ScheduleJob(job, trigger); log.Info($"{job.Key} will run at: {ft:r} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds"); // statefulJob2 will run every three seconds // (but it will delay for ten seconds - and therefore purposely misfire after a few iterations) job = JobBuilder.Create <StatefulDumbJob>() .WithIdentity("statefulJob2", "group1") .UsingJobData(StatefulDumbJob.ExecutionDelay, 10000L) .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger2", "group1") .StartAt(startTime) .WithSimpleSchedule(x => x .WithIntervalInSeconds(3) .RepeatForever() .WithMisfireHandlingInstructionNowWithExistingCount()) // set misfire instructions .Build(); ft = await sched.ScheduleJob(job, trigger); log.Info($"{job.Key} will run at: {ft:r} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds"); log.Info("------- Starting Scheduler ----------------"); // jobs don't start firing until start() has been called... await sched.Start(); log.Info("------- Started Scheduler -----------------"); // sleep for ten minutes for triggers to file.... await Task.Delay(TimeSpan.FromMinutes(10)); log.Info("------- Shutting Down ---------------------"); await sched.Shutdown(true); log.Info("------- Shutdown Complete -----------------"); SchedulerMetaData metaData = await sched.GetMetaData(); log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs."); }
static void Main(string[] args) { RESTApi.ServerUrl = "http://*****:*****@gmail.com"); //msg.To.Add(tmp.user.Email); msg.To.Add("*****@*****.**"); msg.Subject = "Status your work " + DateTime.Now.ToString(); msg.Body = tmp.user.FullName + ", " + tmp.problem.Subject + " " + tmp.state.Status; SmtpClient client = new SmtpClient(); client.UseDefaultCredentials = true; client.Host = "smtp.gmail.com"; client.Port = 587; client.EnableSsl = true; client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Credentials = new NetworkCredential("*****@*****.**", "Qwerty`123"); client.Timeout = 20000; try { client.Send(msg); Console.WriteLine("Mail has been successfully sent!"); } catch (Exception ex) { Console.WriteLine("Fail Has error" + ex.Message); } finally { msg.Dispose(); } tempStudentFiles[tmp.problem.TeacherId].Add(tmp); } catch (Exception ex) { Console.WriteLine(ex.Message); } }; channel.BasicConsume("QStudentFiles", true, consumer); Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } } ); worker.Start(); ISchedulerFactory schedFact = new StdSchedulerFactory(); // get a scheduler IScheduler sched = schedFact.GetScheduler().Result; sched.Start(); IJobDetail job = JobBuilder.Create <HelloJob>() .WithIdentity("myJob", "group1") .Build(); ITrigger trigger = TriggerBuilder.Create() .WithIdentity("myTrigger", "group1") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInMinutes(1) .RepeatForever()) .Build(); sched.ScheduleJob(job, trigger); }
private void ComposeObjects() { var container = new Container(); container.Options.SuppressLifestyleMismatchVerification = true; container.RegisterSingleton <ISettings>(() => Settings.Default); container.Register <IMyDbContext, MyDBContext>(Lifestyle.Transient); container.Register <IInstrumentSource, InstrumentRepository>(Lifestyle.Transient); container.RegisterSingleton <IDataClient>(() => new QDMSClient.QDMSClient( "SERVERCLIENT", "127.0.0.1", Settings.Default.rtDBReqPort, Settings.Default.rtDBPubPort, Settings.Default.hDBPort, Settings.Default.httpPort, Settings.Default.apiKey, useSsl: Settings.Default.useSsl)); container.Register(DataStorageFactory.Get); container.Register <ICountryCodeHelper, CountryCodeHelper>(Lifestyle.Singleton); //These sources provide both real time and historical data var ibRtReg = Lifestyle.Singleton.CreateRegistration <IB>(() => new IB(Settings.Default, new QDMSIBClient.Client(), Settings.Default.rtdClientIBID), container); var ibHdReg = Lifestyle.Singleton.CreateRegistration <IB>(() => new IB(Settings.Default, new QDMSIBClient.Client(), Settings.Default.histClientIBID), container); var binanceReg = Lifestyle.Singleton.CreateRegistration <Binance>(container); var bothSources = new[] { binanceReg }; //Realtime sources var realtimeSources = new Type[] { }; container.Collection.Register <IRealTimeDataSource>(realtimeSources .Select(type => Lifestyle.Singleton.CreateRegistration(type, container)) .Concat(bothSources) .Concat(new[] { ibRtReg })); //Historical sources var historicalSources = new[] { typeof(Yahoo), typeof(FRED), typeof(Quandl), typeof(BarChart) }; container.Collection.Register <IHistoricalDataSource>(historicalSources .Select(type => Lifestyle.Singleton.CreateRegistration(type, container)) .Concat(bothSources) .Concat(new[] { ibHdReg })); //economic release sources var econReleaseSources = new[] { typeof(fx.FXStreet) }; container.Collection.Register <IEconomicReleaseSource>(econReleaseSources .Select(type => Lifestyle.Singleton.CreateRegistration(type, container))); //dividend sources var dividendSources = new[] { typeof(NasdaqDs.Nasdaq) }; container.Collection.Register <IDividendDataSource>(dividendSources .Select(type => Lifestyle.Singleton.CreateRegistration(type, container))); //earnings announcement sources var earningsSources = new[] { typeof(CBOEModule.CBOE) }; container.Collection.Register <IEarningsAnnouncementSource>(earningsSources .Select(type => Lifestyle.Singleton.CreateRegistration(type, container))); //brokers container.Register <IContinuousFuturesBroker, ContinuousFuturesBroker>(Lifestyle.Singleton); container.Register <IRealTimeDataBroker, RealTimeDataBroker>(Lifestyle.Singleton); container.Register <IHistoricalDataBroker, HistoricalDataBroker>(Lifestyle.Singleton); container.Register <IEconomicReleaseBroker, EconomicReleaseBroker>(Lifestyle.Singleton); container.Register <IDividendsBroker, DividendsBroker>(Lifestyle.Singleton); container.Register <IEarningsAnnouncementBroker, EarningsAnnouncementBroker>(Lifestyle.Singleton); //servers container.Register <IRealTimeDataServer, RealTimeDataServer>(Lifestyle.Singleton); container.Register <IHistoricalDataServer, HistoricalDataServer>(Lifestyle.Singleton); //scheduler container.Register <IJobFactory, JobFactory>(Lifestyle.Singleton); var quartzSettings = QuartzUtils.GetQuartzSettings(Settings.Default.databaseType); var factory = new StdSchedulerFactory(quartzSettings); container.RegisterSingleton(() => factory.GetScheduler()); container.RegisterInitializer <IScheduler>(scheduler => { scheduler.JobFactory = container.GetInstance <IJobFactory>(); }); //http server container.Register <INancyBootstrapper, CustomBootstrapper>(); //UI container.Register(() => DialogCoordinator.Instance); //ViewModels container.Register <MainViewModel>(); var vm = container.GetInstance <MainViewModel>(); var mainWindow = new MainWindow(vm, container.GetInstance <IDataClient>()); mainWindow.Show(); }
public virtual async Task Run() { ILog log = LogProvider.GetLogger(typeof(CalendarExample)); log.Info("------- Initializing ----------------------"); // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler sched = await sf.GetScheduler(); log.Info("------- Initialization Complete -----------"); log.Info("------- Scheduling Jobs -------------------"); // Add the holiday calendar to the schedule AnnualCalendar holidays = new AnnualCalendar(); // fourth of July (July 4) DateTime fourthOfJuly = new DateTime(DateTime.UtcNow.Year, 7, 4); holidays.SetDayExcluded(fourthOfJuly, true); // halloween (Oct 31) DateTime halloween = new DateTime(DateTime.UtcNow.Year, 10, 31); holidays.SetDayExcluded(halloween, true); // christmas (Dec 25) DateTime christmas = new DateTime(DateTime.UtcNow.Year, 12, 25); holidays.SetDayExcluded(christmas, true); // tell the schedule about our holiday calendar await sched.AddCalendar("holidays", holidays, false, false); // schedule a job to run hourly, starting on halloween // at 10 am DateTimeOffset runDate = DateBuilder.DateOf(0, 0, 10, 31, 10); IJobDetail job = JobBuilder.Create <SimpleJob>() .WithIdentity("job1", "group1") .Build(); ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartAt(runDate) .WithSimpleSchedule(x => x.WithIntervalInHours(1).RepeatForever()) .ModifiedByCalendar("holidays") .Build(); // schedule the job and print the first run date DateTimeOffset firstRunTime = await sched.ScheduleJob(job, trigger); // print out the first execution date. // Note: Since Halloween (Oct 31) is a holiday, then // we will not run until the next day! (Nov 1) log.Info($"{job.Key} will run at: {firstRunTime:r} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds"); // All of the jobs have been added to the scheduler, but none of the jobs // will run until the scheduler has been started log.Info("------- Starting Scheduler ----------------"); await sched.Start(); // wait 30 seconds: // note: nothing will run log.Info("------- Waiting 30 seconds... --------------"); // wait 30 seconds to show jobs await Task.Delay(TimeSpan.FromSeconds(30)); // executing... // shut down the scheduler log.Info("------- Shutting Down ---------------------"); await sched.Shutdown(true); log.Info("------- Shutdown Complete -----------------"); SchedulerMetaData metaData = await sched.GetMetaData(); log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs."); }
/// <summary> /// 构造函数 /// </summary> public Engine() { Jobs = new Dictionary <JobKey, TriggerKey>(); Scheduler = StdSchedulerFactory.GetDefaultScheduler(); }
public static void MyClassInitialize(TestContext testContext) { var schedulerFactory = new StdSchedulerFactory(); scheduler = schedulerFactory.GetScheduler(); }
public static void Start() { #region Scheduler Envia Email Sms IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler(); scheduler.Start(); IJobDetail jobEmailSms = JobBuilder.Create <EnvioEmailSms>().Build(); ITrigger triggerEmailSms = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(120) // Chama serviço para enviar Email e Sms de 2 em 2 minutos. .RepeatForever()) .Build(); scheduler.ScheduleJob(jobEmailSms, triggerEmailSms); #endregion #region Scheduler Gera Cotação IScheduler schedulerGeraCotacao = StdSchedulerFactory.GetDefaultScheduler(); schedulerGeraCotacao.Start(); IJobDetail jobGeraCotacao = JobBuilder.Create <GeraCotacao>().Build(); ITrigger triggerGeraCotacao = TriggerBuilder.Create() .WithIdentity("trigger2", "group2") .StartNow() .WithCronSchedule("0 00 12 * * ?") // Ás 12:00:00 é gerado cotação caso exista pedidos .Build(); schedulerGeraCotacao.ScheduleJob(jobGeraCotacao, triggerGeraCotacao); #endregion #region Scheduler Fechar Cotação IScheduler schedulerFecharCotacao = StdSchedulerFactory.GetDefaultScheduler(); schedulerFecharCotacao.Start(); IJobDetail jobFecharCotacao = JobBuilder.Create <FecharCotacao>().Build(); ITrigger triggerFecharCotacao = TriggerBuilder.Create() .WithIdentity("trigger3", "group3") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(2) // Chama serviço para fechar cotação de 2 em 2 minutos. .RepeatForever()) .Build(); schedulerFecharCotacao.ScheduleJob(jobFecharCotacao, triggerFecharCotacao); #endregion #region Scheduler Notificacoes e Alertas IScheduler schedulerNotificacoesAlertas = StdSchedulerFactory.GetDefaultScheduler(); schedulerNotificacoesAlertas.Start(); IJobDetail jobNotificacoesAlertas = JobBuilder.Create <NotificacoesAlertas>().Build(); ITrigger triggerNotificacoesAlertas = TriggerBuilder.Create() .WithIdentity("trigger4", "group4") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(2) // Chama serviço para enviar notificações e alertas de 2 em 2 minutos. .RepeatForever()) .Build(); schedulerNotificacoesAlertas.ScheduleJob(jobNotificacoesAlertas, triggerNotificacoesAlertas); #endregion #region Scheduler Pagamentos / Gera Fatura Fornecedores IScheduler schedulerPagamentosFatura = StdSchedulerFactory.GetDefaultScheduler(); schedulerPagamentosFatura.Start(); IJobDetail jobPagamentosFatura = JobBuilder.Create <GeraFatura>().Build(); ITrigger triggerPagamentosFatura = TriggerBuilder.Create() .WithIdentity("trigger5", "group5") .StartNow() .WithCronSchedule("0 00 01 * * ?") // Ás 00:01:00 são gerados boletos .Build(); schedulerPagamentosFatura.ScheduleJob(jobPagamentosFatura, triggerPagamentosFatura); #endregion #region Scheduler Pagamentos / Gera Mensalidade Membros IScheduler schedulerPagamentosMensalidade = StdSchedulerFactory.GetDefaultScheduler(); schedulerPagamentosMensalidade.Start(); IJobDetail jobPagamentosMensalidade = JobBuilder.Create <GeraMensalidade>().Build(); ITrigger triggerPagamentosMensalidade = TriggerBuilder.Create() .WithIdentity("trigger6", "group6") .StartNow() .WithCronSchedule("0 00 01 * * ?") // Ás 00:01:00 são geradas mensalidades .Build(); schedulerPagamentosMensalidade.ScheduleJob(jobPagamentosMensalidade, triggerPagamentosMensalidade); #endregion }
public virtual void Run() { ILog log = LogManager.GetLogger(typeof(JobExceptionExample)); log.Info("------- Initializing ----------------------"); // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler sched = sf.GetScheduler(); log.Info("------- Initialization Complete ------------"); log.Info("------- Scheduling Jobs -------------------"); // jobs can be scheduled before start() has been called // get a "nice round" time a few seconds in the future... DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 15); // badJob1 will run every 10 seconds // this job will throw an exception and refire // immediately IJobDetail job = JobBuilder.Create <BadJob1>() .WithIdentity("badJob1", "group1") .UsingJobData("denominator", "0") .Build(); ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever()) .Build(); DateTimeOffset ft = sched.ScheduleJob(job, trigger); log.Info(job.Key + " will run at: " + ft + " and repeat: " + trigger.RepeatCount + " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds"); // badJob2 will run every five seconds // this job will throw an exception and never // refire job = JobBuilder.Create <BadJob2>() .WithIdentity("badJob2", "group1") .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger2", "group1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()) .Build(); ft = sched.ScheduleJob(job, trigger); log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, ft.ToString("r"), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds)); log.Info("------- Starting Scheduler ----------------"); // jobs don't start firing until start() has been called... sched.Start(); log.Info("------- Started Scheduler -----------------"); // sleep for 30 seconds try { Thread.Sleep(TimeSpan.FromSeconds(30)); } catch (ThreadInterruptedException) { } log.Info("------- Shutting Down ---------------------"); sched.Shutdown(false); log.Info("------- Shutdown Complete -----------------"); SchedulerMetaData metaData = sched.GetMetaData(); log.Info(string.Format("Executed {0} jobs.", metaData.NumberOfJobsExecuted)); }
private void Init() { SchedFact = new StdSchedulerFactory((NameValueCollection)ConfigurationManager.GetSection("quartz")); Scheduler = SchedFact.GetScheduler(); Scheduler.Start(); }
/// <summary> /// Shutdown the scheduler. /// </summary> public static void ShutdownScheduler() { var scheduler = StdSchedulerFactory.GetDefaultScheduler(); scheduler.Shutdown(); }
public static void Start() { IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler(); scheduler.Start(); IJobDetail diretionToPayJob = JobBuilder.Create <DirectionToPayJob>().Build(); ITrigger trigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(3, 0)) ) .Build(); // for test /*ITrigger trigger1 = TriggerBuilder.Create() * .WithIdentity("trigger1", "group1") * .StartNow() * .WithSimpleSchedule(x => x * .WithIntervalInSeconds(30) * .RepeatForever()) * .Build(); */ scheduler.ScheduleJob(diretionToPayJob, trigger); IJobDetail coommissionNotificationJob = JobBuilder.Create <CommissionNotificationJob>().Build(); ITrigger coommissionNotificationTrigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(3, 0)) ) .Build(); scheduler.ScheduleJob(coommissionNotificationJob, coommissionNotificationTrigger); CommissionHelper.SendNotifications();//todo убрать после отладки IJobDetail checkSuspensionPeriodsJob = JobBuilder.Create <CommissionNotificationJob>().Build(); ITrigger checkSuspensionPeriodsTrigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(3, 0)) ) .Build(); scheduler.ScheduleJob(checkSuspensionPeriodsJob, checkSuspensionPeriodsTrigger); IJobDetail checkRefPassedDaysJob = JobBuilder.Create <CheckRefPassedDaysJob>().Build(); ITrigger checkRefPassedDaysTrigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule (s => s.WithIntervalInHours(24) .OnEveryDay() .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(4, 0)) ) .Build(); scheduler.ScheduleJob(checkRefPassedDaysJob, checkRefPassedDaysTrigger); IJobDetail diretionToPaymentJob = JobBuilder.Create <OBKDirectionToPaymentJob>().Build(); //ITrigger paymenTrigger = TriggerBuilder.Create() // .WithDailyTimeIntervalSchedule // (s => // s.WithIntervalInHours(24) // .OnEveryDay() // .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(3, 0)) // ) // .Build(); ITrigger trigger1 = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(30) .RepeatForever()) .Build(); scheduler.ScheduleJob(diretionToPaymentJob, trigger1); IJobDetail certificateOfComplection = JobBuilder.Create <OBKCertificateOfCompletion>().Build(); //ITrigger paymenTrigger = TriggerBuilder.Create() // .WithDailyTimeIntervalSchedule // (s => // s.WithIntervalInHours(24) // .OnEveryDay() // .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(3, 0)) // ) // .Build(); ITrigger trigger2 = TriggerBuilder.Create() .WithIdentity("trigger2", "group2") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(30) .RepeatForever()) .Build(); scheduler.ScheduleJob(certificateOfComplection, trigger2); }
public void ConfigureServices(IServiceCollection services) { services .AddControllers(); var scheduler = CreateScheduler(); services .AddElsa() .AddTaskExecutingServer() .AddHttpActivities() .AddTimerActivities(options => options.Configure(x => x.SweepInterval = Period.FromSeconds(10))) .AddEmailActivities(options => options.Bind(Configuration.GetSection("Smtp"))) .AddMassTransitSchedulingActivities(options => { options.SchedulerAddress = new Uri("rabbitmq://localhost/sample_quartz_scheduler"); }) .AddWorkflow <CartTrackingWorkflow>() .AddScoped <ICarts, Carts>() .AddSingleton(scheduler) // configures MassTransit to integrate with the built-in dependency injection .AddMassTransit(CreateBus, ConfigureMassTransit) // Add a hosted service to stat and stop the quartz scheduler .AddSingleton <IHostedService, QuartzHostedService>(); void ConfigureMassTransit(IServiceCollectionConfigurator configurator) { // Configure scheduler service consumers. configurator.AddConsumer <ScheduleMessageConsumer>(); configurator.AddConsumer <CancelScheduledMessageConsumer>(); // configure workflow consumers configurator.AddWorkflowConsumer <CartCreated>(); configurator.AddWorkflowConsumer <CartItemAdded>(); configurator.AddWorkflowConsumer <OrderSubmitted>(); configurator.AddWorkflowConsumer <CartExpiredEvent>(); // host fake service consumers configurator.AddConsumer <CartRemovedConsumer>(); } // local function to create the bus IBusControl CreateBus(IServiceProvider serviceProvider) { var bus = Bus.Factory.CreateUsingRabbitMq(cfg => { var host = cfg.Host(new Uri("rabbitmq://localhost"), h => { h.Username("guest"); h.Password("guest"); }); cfg.UseMessageScheduler(new Uri("rabbitmq://localhost/sample_quartz_scheduler")); cfg.ReceiveEndpoint(host, "shopping_cart_service", ep => { ep.ConfigureConsumer <CartRemovedConsumer>(serviceProvider); }); cfg.ReceiveEndpoint(host, "shopping_cart_state", ep => { ep.PrefetchCount = 16; ep.UseMessageRetry(r => r.Interval(2, 100)); // Consume all workflow messages from the same queue. ep.ConfigureWorkflowConsumer <CartCreated>(serviceProvider); ep.ConfigureWorkflowConsumer <CartItemAdded>(serviceProvider); ep.ConfigureWorkflowConsumer <OrderSubmitted>(serviceProvider); ep.ConfigureWorkflowConsumer <CartExpiredEvent>(serviceProvider); }); // Should use external process scheduler service // https://github.com/MassTransit/MassTransit/tree/develop/src/Samples/MassTransit.QuartzService cfg.ReceiveEndpoint(host, "sample_quartz_scheduler", e => { // For MT4.0, prefetch must be set for Quartz prior to anything else e.PrefetchCount = 1; cfg.UseMessageScheduler(e.InputAddress); e.ConfigureConsumer <ScheduleMessageConsumer>(serviceProvider); e.ConfigureConsumer <CancelScheduledMessageConsumer>(serviceProvider); }); }); scheduler.JobFactory = new MassTransitJobFactory(bus); return(bus); } IScheduler CreateScheduler() { LogProvider.SetCurrentLogProvider(new QuartzConsoleLogProvider()); ISchedulerFactory schedulerFactory = new StdSchedulerFactory(new NameValueCollection() { { "quartz.scheduler.instanceName", "Sample-QuartzScheduler" }, { "quartz.scheduler.instanceId", "AUTO" }, { "quartz.threadPool.type", "Quartz.Simpl.SimpleThreadPool, Quartz" }, { "quartz.threadPool.threadCount", "4" }, { "quartz.jobStore.misfireThreshold", "60000" }, { "quartz.jobStore.type", "Quartz.Simpl.RAMJobStore, Quartz" }, }); var scheduler = schedulerFactory.GetScheduler().GetAwaiter().GetResult(); return(scheduler); } }
static async Task Main() { #region serilog Log.Logger = new LoggerConfiguration() .WriteTo.ColoredConsole() .CreateLogger(); LogManager.Use <SerilogFactory>(); #endregion Console.Title = "Samples.QuartzScheduler.Scheduler"; var endpointConfiguration = new EndpointConfiguration("Samples.QuartzScheduler.Scheduler"); endpointConfiguration.UseTransport <LearningTransport>(); #region Configuration var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); var schedulerFactory = new StdSchedulerFactory(); var scheduler = await schedulerFactory.GetScheduler() .ConfigureAwait(false); // inject the endpointInstance into the scheduler context scheduler.SetEndpointInstance(endpointInstance); await scheduler.Start() .ConfigureAwait(false); #endregion #region scheduleJob // define the job and tie it to the SendMessageJob class var job = JobBuilder.Create <SendMessageJob>() .WithIdentity("job1", "group1") .Build(); // Trigger the job to run now, and then repeat every 3 seconds var trigger = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartNow() .WithSimpleSchedule( action: builder => { builder .WithIntervalInSeconds(3) .RepeatForever(); }) .Build(); // Tell quartz to schedule the job using our trigger await scheduler.ScheduleJob(job, trigger) .ConfigureAwait(false); #endregion Console.WriteLine("Press any key to exit"); Console.ReadKey(); #region shutdown await scheduler.Shutdown() .ConfigureAwait(false); await endpointInstance.Stop() .ConfigureAwait(false); #endregion }
static TaskScheduler() { factory = new StdSchedulerFactory(); }
public async Task Stop() { var scheduler = await StdSchedulerFactory.GetDefaultScheduler(); await scheduler.Shutdown(); }
public async Task Run(ILog log) { log.Info("------- Initializing ----------------------"); // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(); IScheduler sched = sf.GetScheduler(); log.Info("------- Initialization Complete ------------"); log.Info("------- Scheduling Jobs -------------------"); // jobs can be scheduled before start() has been called // get a "nice round" time a few seconds in the future... DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 15); // badJob1 will run every 10 seconds // this job will throw an exception and refire // immediately IJobDetail job = JobBuilder.Create <BadJob>() .WithIdentity("badJob1", "group1") .UsingJobData("denominator", "0") .Build(); ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithIntervalInSeconds(10).RepeatForever()) .Build(); DateTimeOffset ft = sched.ScheduleJob(job, trigger); log.Info(job.Key + " will run at: " + ft + " and repeat: " + trigger.RepeatCount + " times, every " + trigger.RepeatInterval.TotalSeconds + " seconds"); // badJob2 will run every five seconds // this job will throw an exception and never // refire job = JobBuilder.Create <BadJob2>() .WithIdentity("badJob2", "group1") .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger2", "group1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever()) .Build(); ft = sched.ScheduleJob(job, trigger); log.Info($"{job.Key} will run at: {ft.ToString("r")} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds"); log.Info("------- Starting Scheduler ----------------"); // jobs don't start firing until start() has been called... sched.Start(); log.Info("------- Started Scheduler -----------------"); // sleep for 30 seconds await Task.Delay(TimeSpan.FromSeconds(30)); log.Info("------- Shutting Down ---------------------"); sched.Shutdown(false); log.Info("------- Shutdown Complete -----------------"); SchedulerMetaData metaData = sched.GetMetaData(); log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs."); }
/** **@ brief: this method starts the Quartz which is a thread which automatically starts on the given time * first it will check the password if password is correct then it will shutdown the Quartz first and then * starts the Day Schedular and KeepAliveJob Quartz *@ Params: string password *@ return: bool **/ public bool startMainQuartz(string password) { bool isSuccess = false; try { if (password == "abc") { ////////////////////////////// shutdown jobs ///////////////////////// var schedulerFactory = new StdSchedulerFactory(); var scheduler = schedulerFactory.GetScheduler(); var keepAliveJob = JobBuilder.Create <KeepAliveJob>().Build(); var keepAliveTrigger = TriggerBuilder.Create() .WithSimpleSchedule(x => x.WithIntervalInMinutes(10).RepeatForever()) .Build(); scheduler.ScheduleJob(keepAliveJob, keepAliveTrigger); scheduler.Shutdown(); var schedulerFact = new StdSchedulerFactory(); var sched = schedulerFact.GetScheduler(); var DaySchedular = JobBuilder.Create <DaySchedular>().Build(); var DaySchedularTrigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule(x => x.WithIntervalInHours(24).OnEveryDay().StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(4, 0))) .Build(); sched.ScheduleJob(DaySchedular, DaySchedularTrigger); sched.Shutdown(); ////////////////////////////////////// start jobs ////////////////////////////////////// var _schedulerFactory = new StdSchedulerFactory(); var _scheduler = _schedulerFactory.GetScheduler(); var _keepAliveJob = JobBuilder.Create <KeepAliveJob>().Build(); var _keepAliveTrigger = TriggerBuilder.Create() .WithSimpleSchedule(x => x.WithIntervalInMinutes(10).RepeatForever()) .Build(); _scheduler.ScheduleJob(_keepAliveJob, _keepAliveTrigger); _scheduler.Start(); var _schedulerFact = new StdSchedulerFactory(); var _sched = _schedulerFact.GetScheduler(); var _DaySchedular = JobBuilder.Create <DaySchedular>().Build(); var _DaySchedularTrigger = TriggerBuilder.Create() .WithDailyTimeIntervalSchedule(x => x.WithIntervalInHours(24).OnEveryDay().StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(4, 0))) .Build(); _sched.ScheduleJob(_DaySchedular, _DaySchedularTrigger); _sched.Start(); isSuccess = true; } else { isSuccess = false; } } catch (Exception ex) { isSuccess = false; } return(isSuccess); }
public static void Start() { ISchedulerFactory sf = new StdSchedulerFactory(); #region service intelitrak IJobDetail jobGpsTrackerIntelitrak = JobBuilder.Create <GpsTrackerIntelitrak>() .WithIdentity("jobGpsTrackerIntelitrak") .Build(); ITrigger triggerGpsTrackerIntelitrak = TriggerBuilder.Create() .WithIdentity("triggerGpsTrackerIntelitrak") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(180) .RepeatForever()) .Build(); Quartz.IScheduler scGpsTrackerIntelitrak = sf.GetScheduler(); scGpsTrackerIntelitrak.ScheduleJob(jobGpsTrackerIntelitrak, triggerGpsTrackerIntelitrak); scGpsTrackerIntelitrak.Start(); #endregion #region service solofleet IJobDetail jobGpsTrackerSolofleet = JobBuilder.Create <GpsTrackerSoloflet>() .WithIdentity("jobGpsTrackerSolofleet") .Build(); ITrigger triggerGpsTrackerSolofleet = TriggerBuilder.Create() .WithIdentity("triggerGpsTrackerSolofleet") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(180) .RepeatForever()) .Build(); Quartz.IScheduler scGpsTrackerSolofleet = sf.GetScheduler(); scGpsTrackerSolofleet.ScheduleJob(jobGpsTrackerSolofleet, triggerGpsTrackerSolofleet); scGpsTrackerSolofleet.Start(); #endregion #region service trekq IJobDetail jobGpsTrackerTrekq = JobBuilder.Create <GpsTrackerTrekq>() .WithIdentity("jobGpsTrackerTrekq") .Build(); ITrigger triggerGpsTrackerTreq = TriggerBuilder.Create() .WithIdentity("triggerGpsTrackerTreq") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(180) .RepeatForever()) .Build(); Quartz.IScheduler scGpsTrackerTrekq = sf.GetScheduler(); scGpsTrackerTrekq.ScheduleJob(jobGpsTrackerTrekq, triggerGpsTrackerTreq); scGpsTrackerTrekq.Start(); #endregion #region service update data truk IJobDetail jobUpdateDataTruck = JobBuilder.Create <UpdateDataTruk>() .WithIdentity("jobUpdateDataTruck") .Build(); ITrigger triggerUpdateDataTruck = TriggerBuilder.Create() .WithIdentity("triggerUpdateDataTruck") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(120) .RepeatForever()) .Build(); Quartz.IScheduler scUpdateDataTruck = sf.GetScheduler(); scUpdateDataTruck.ScheduleJob(jobUpdateDataTruck, triggerUpdateDataTruck); scUpdateDataTruck.Start(); #endregion #region service Notif IJobDetail jobNotif = JobBuilder.Create <Notif>() .WithIdentity("jobNotif") .Build(); ITrigger triggerNotif = TriggerBuilder.Create() .WithIdentity("triggerNotif") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(120) .RepeatForever()) .Build(); Quartz.IScheduler scNotif = sf.GetScheduler(); scNotif.ScheduleJob(jobNotif, triggerNotif); scNotif.Start(); #endregion }
public ServiceRunner() { scheduler = StdSchedulerFactory.GetDefaultScheduler(); }
public virtual async Task Run(bool inClearJobs, bool inScheduleJobs) { NameValueCollection properties = new NameValueCollection { ["quartz.scheduler.instanceName"] = "TestScheduler", ["quartz.scheduler.instanceId"] = "instance_one", ["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz", ["quartz.threadPool.threadCount"] = "5", ["quartz.jobStore.misfireThreshold"] = "60000", ["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz", ["quartz.jobStore.useProperties"] = "false", ["quartz.jobStore.dataSource"] = "default", ["quartz.jobStore.tablePrefix"] = "QRTZ_", ["quartz.jobStore.clustered"] = "true", ["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz", ["quartz.dataSource.default.connectionString"] = TestConstants.SqlServerConnectionString, ["quartz.dataSource.default.provider"] = TestConstants.DefaultSqlServerProvider, ["quartz.serializer.type"] = "json" }; // if running SQLite we need this // properties["quartz.jobStore.lockHandler.type"] = "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz"; // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(properties); IScheduler sched = await sf.GetScheduler(); if (inClearJobs) { log.Warn("***** Deleting existing jobs/triggers *****"); await sched.Clear(); } log.Info("------- Initialization Complete -----------"); if (inScheduleJobs) { log.Info("------- Scheduling Jobs ------------------"); string schedId = sched.SchedulerInstanceId; int count = 1; IJobDetail job = JobBuilder.Create <SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(5))) .Build(); log.InfoFormat("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds); count++; job = JobBuilder.Create <SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(2, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(5))) .Build(); log.Info($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds"); await sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create <SimpleRecoveryStatefulJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(3))) .Build(); log.Info($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds"); await sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create <SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromSeconds(4))) .Build(); log.Info($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} & repeat: {trigger.RepeatCount}/{trigger.RepeatInterval}"); await sched.ScheduleJob(job, trigger); count++; job = JobBuilder.Create <SimpleRecoveryJob>() .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where .RequestRecovery() // ask scheduler to re-execute this job if it was in progress when the scheduler went down... .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("triger_" + count, schedId) .StartAt(DateBuilder.FutureDate(1, IntervalUnit.Second)) .WithSimpleSchedule(x => x.WithRepeatCount(20).WithInterval(TimeSpan.FromMilliseconds(4500))) .Build(); log.Info($"{job.Key} will run at: {trigger.GetNextFireTimeUtc()} & repeat: {trigger.RepeatCount}/{trigger.RepeatInterval}"); await sched.ScheduleJob(job, trigger); } // jobs don't start firing until start() has been called... log.Info("------- Starting Scheduler ---------------"); await sched.Start(); log.Info("------- Started Scheduler ----------------"); log.Info("------- Waiting for one hour... ----------"); await Task.Delay(TimeSpan.FromHours(1)); log.Info("------- Shutting Down --------------------"); await sched.Shutdown(); log.Info("------- Shutdown Complete ----------------"); }
public async Task RunAsync() { IScheduler scheduler = await StdSchedulerFactory.GetDefaultScheduler(); DateTimeOffset startTime = DateTimeOffset.Now.AddSeconds(3); #region 作业1 每3秒执行一次 IJobDetail job = JobBuilder.Create <LogTimeJob>() .WithIdentity("job1", "jobGroup1") .SetJobData(new JobDataMap { { LogTimeJob.NumExecutions, 0 }, { LogTimeJob.ExecutionDelay, 10 } }) .Build(); ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger1", "triggerGroup1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(3)).RepeatForever()) .Build(); DateTimeOffset df = await scheduler.ScheduleJob(job, trigger); ConsoleExtend.WriteLineRed($"触发器【{trigger.Key}】 作业【{job.Key}】 下次执行时间【{df.LocalDateTime.ToString("r")}】" + $" 执行时间间隔【{trigger.RepeatInterval.Seconds}】 重复次数【{trigger.RepeatCount}】"); #endregion #region 作业2 每3秒执行一次 job = JobBuilder.Create <LogTimeJob>() .WithIdentity("job2", "jobGroup1") .SetJobData(new JobDataMap { { LogTimeJob.NumExecutions, 0 }, { LogTimeJob.ExecutionDelay, 10 } }) .Build(); trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger2", "triggerGroup1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(3)).RepeatForever().WithMisfireHandlingInstructionNowWithExistingCount()) .Build(); df = await scheduler.ScheduleJob(job, trigger); ConsoleExtend.WriteLineRed($"触发器【{trigger.Key}】 作业【{job.Key}】 下次执行时间【{df.LocalDateTime.ToString("r")}】" + $" 执行时间间隔【{trigger.RepeatInterval.Seconds}】 重复次数【{trigger.RepeatCount}】"); #endregion #region 给作业1 添加一个新的触发器 trigger = (ISimpleTrigger)TriggerBuilder.Create() .WithIdentity("trigger3", "triggerGroup1") .StartAt(startTime) .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromSeconds(3)).RepeatForever().WithMisfireHandlingInstructionNowWithExistingCount()) .ForJob("job1", "jobGroup1") .Build(); df = await scheduler.ScheduleJob(trigger); ConsoleExtend.WriteLineRed($"触发器【{trigger.Key}】 作业【{trigger.JobKey}】 下次执行时间【{df.LocalDateTime.ToString("r")}】" + $" 执行时间间隔【{trigger.RepeatInterval.Seconds}】 重复次数【{trigger.RepeatCount}】"); #endregion await scheduler.Start(); await Task.Delay(TimeSpan.FromMinutes(2)); await scheduler.Shutdown(); }
public void StressTest() { NameValueCollection properties = new NameValueCollection(); properties["quartz.scheduler.instanceName"] = "TestScheduler"; properties["quartz.scheduler.instanceId"] = "instance_one"; properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; properties["quartz.threadPool.threadCount"] = "10"; properties["quartz.threadPool.threadPriority"] = "Normal"; properties["quartz.jobStore.misfireThreshold"] = "60000"; properties["quartz.jobStore.type"] = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz"; properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz"; properties["quartz.jobStore.useProperties"] = "false"; properties["quartz.jobStore.dataSource"] = "default"; properties["quartz.jobStore.tablePrefix"] = "QRTZ_"; properties["quartz.jobStore.clustered"] = "false"; properties["quartz.jobStore.driverDelegateType"] = "Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz"; string connectionString = "Server=(local);Database=quartz;Trusted_Connection=True;"; properties["quartz.dataSource.default.connectionString"] = connectionString; properties["quartz.dataSource.default.provider"] = "SqlServer-20"; // First we must get a reference to a scheduler ISchedulerFactory sf = new StdSchedulerFactory(properties); IScheduler sched = sf.GetScheduler(); try { sched.Clear(); JobDetailImpl lonelyJob = new JobDetailImpl("lonelyJob", "lonelyGroup", typeof(SimpleRecoveryJob)); lonelyJob.Durable = true; lonelyJob.RequestsRecovery = true; sched.AddJob(lonelyJob, false); sched.AddJob(lonelyJob, true); string schedId = sched.SchedulerInstanceId; JobDetailImpl job = new JobDetailImpl("job_to_use", schedId, typeof(SimpleRecoveryJob)); for (int i = 0; i < 100000; ++i) { IOperableTrigger trigger = new SimpleTriggerImpl("stressing_simple", SimpleTriggerImpl.RepeatIndefinitely, TimeSpan.FromSeconds(1)); trigger.StartTimeUtc = DateTime.Now.AddMilliseconds(i); sched.ScheduleJob(job, trigger); } for (int i = 0; i < 100000; ++i) { IOperableTrigger ct = new CronTriggerImpl("stressing_cron", "0/1 * * * * ?"); ct.StartTimeUtc = DateTime.Now.AddMilliseconds(i); sched.ScheduleJob(job, ct); } Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); sched.Start(); Thread.Sleep(TimeSpan.FromMinutes(3)); stopwatch.Stop(); Console.WriteLine("Took: " + stopwatch.Elapsed); } finally { sched.Shutdown(false); } }
public void Start() { // construct a scheduler factory ISchedulerFactory schedFact = new StdSchedulerFactory(); // get a scheduler sched = schedFact.GetScheduler(); sched.Start(); //{ // IJobDetail job = JobBuilder.Create<Noop_IJob>() // .WithIdentity("myJob1", "group1") // .Build(); // // Trigger the job to run now, and then every 40 seconds // ITrigger trigger = TriggerBuilder.Create() // .WithIdentity("myTrigger1", "group1") // .StartNow() // .WithSimpleSchedule(x => x // .WithIntervalInSeconds(10) // .RepeatForever()) // .Build(); // sched.ScheduleJob(job, trigger); //} { IJobDetail job = JobBuilder.Create <WebRequest>() .WithIdentity("myJob2", "group1") .Build(); // Trigger the job to run now, and then every 40 seconds ITrigger trigger = TriggerBuilder.Create() .WithIdentity("myTrigger2", "group1") .StartNow() .WithSimpleSchedule(x => x .WithIntervalInSeconds(10) .RepeatForever()) .Build(); sched.ScheduleJob(job, trigger); } //{ // IJobDetail job = JobBuilder.Create<Noop_BaseJob>() // .WithIdentity("myJob3", "group1") // .Build(); // // Trigger the job to run now, and then every 40 seconds // ITrigger trigger = TriggerBuilder.Create() // .WithIdentity("myTrigger3", "group1") // .StartNow() // .WithSimpleSchedule(x => x // .WithIntervalInSeconds(10) // .RepeatForever()) // .Build(); // sched.ScheduleJob(job, trigger); //} }
public void Run() { ILog log = LogManager.GetLogger(typeof(PriorityExample)); log.Info("------- Initializing ----------------------"); // First we must get a reference to a scheduler NameValueCollection properties = new NameValueCollection(); properties["quartz.scheduler.instanceName"] = "PriorityExampleScheduler"; // Set thread count to 1 to force Triggers scheduled for the same time to // to be ordered by priority. properties["quartz.threadPool.threadCount"] = "1"; properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; properties["quartz.jobStore.type"] = "Quartz.Simpl.RAMJobStore, Quartz"; ISchedulerFactory sf = new StdSchedulerFactory(properties); IScheduler sched = sf.GetScheduler(); log.Info("------- Initialization Complete -----------"); log.Info("------- Scheduling Jobs -------------------"); IJobDetail job = JobBuilder.Create <TriggerEchoJob>() .WithIdentity("TriggerEchoJob") .Build(); // All three triggers will fire their first time at the same time, // ordered by their priority, and then repeat once, firing in a // staggered order that therefore ignores priority. // // We should see the following firing order: // 1. Priority10Trigger15SecondRepeat // 2. Priority5Trigger10SecondRepeat // 3. Priority1Trigger5SecondRepeat // 4. Priority1Trigger5SecondRepeat // 5. Priority5Trigger10SecondRepeat // 6. Priority10Trigger15SecondRepeat // Calculate the start time of all triggers as 5 seconds from now DateTimeOffset startTime = DateBuilder.FutureDate(5, DateBuilder.IntervalUnit.Second); // First trigger has priority of 1, and will repeat after 5 seconds ITrigger trigger1 = TriggerBuilder.Create() .WithIdentity("Priority1Trigger5SecondRepeat") .StartAt(startTime) .WithSimpleSchedule(x => x.WithRepeatCount(1).WithIntervalInSeconds(5)) .WithPriority(1) .ForJob(job) .Build(); // Second trigger has default priority of 5 (default), and will repeat after 10 seconds ITrigger trigger2 = TriggerBuilder.Create() .WithIdentity("Priority5Trigger10SecondRepeat") .StartAt(startTime) .WithSimpleSchedule(x => x.WithRepeatCount(1).WithIntervalInSeconds(10)) .ForJob(job) .Build(); // Third trigger has priority 10, and will repeat after 15 seconds ITrigger trigger3 = TriggerBuilder.Create() .WithIdentity("Priority10Trigger15SecondRepeat") .StartAt(startTime) .WithSimpleSchedule(x => x.WithRepeatCount(1).WithIntervalInSeconds(15)) .WithPriority(10) .ForJob(job) .Build(); // Tell quartz to schedule the job using our trigger sched.ScheduleJob(job, trigger1); sched.ScheduleJob(trigger2); sched.ScheduleJob(trigger3); // Start up the scheduler (nothing can actually run until the // scheduler has been started) sched.Start(); log.Info("------- Started Scheduler -----------------"); // wait long enough so that the scheduler as an opportunity to // fire the triggers log.Info("------- Waiting 30 seconds... -------------"); try { Thread.Sleep(TimeSpan.FromSeconds(30)); } catch (ThreadInterruptedException) { } // shut down the scheduler log.Info("------- Shutting Down ---------------------"); sched.Shutdown(true); log.Info("------- Shutdown Complete -----------------"); }
public void Initialize() { lock (SyncRoot) { if (_scheduler != null) return; var schedulerFactory = new StdSchedulerFactory(); _scheduler = schedulerFactory.GetScheduler(); _scheduler.AddGlobalJobListener(new GlobalJobListener()); } }