public void ExecuteScheduler() { try { StdSchedulerFactory factory = new StdSchedulerFactory(); Quartz.IScheduler scheduler = factory.GetScheduler(); // and start it off scheduler.Start(); // define the job and tie it to our HelloJob class IJobDetail job = JobBuilder.Create <ParseJob>() .WithIdentity("job1", "group1") .Build(); // Trigger the job to run now, and then repeat every 10 seconds ITrigger trigger = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartNow() .WithSimpleSchedule(x => x .WithInterval(new TimeSpan(10, 0, 0, 0)) .RepeatForever()) .Build(); // Tell quartz to schedule the job using our trigger scheduler.ScheduleJob(job, trigger); } catch (SchedulerException se) { Console.WriteLine(se); } }
public void Start() { _logger.Info($"Starting Scheduler: {_options.Schedule}"); _scheduler.Start(); var job = JobBuilder.Create <RunTimeExecutor>() .WithIdentity("Job", "TFL") .StoreDurably(false) .RequestRecovery(false) .WithDescription("Transformalize Quartz.Net Job") .UsingJobData("Cfg", _options.Arrangement) .UsingJobData("Shorthand", _options.Shorthand) .UsingJobData("CommandLine.Mode", _options.Mode) .UsingJobData("CommandLine.Format", _options.Format) .UsingJobData("Schedule", _options.Schedule) .Build(); var trigger = TriggerBuilder.Create() .WithIdentity("Trigger", "TFL") .StartNow() .WithCronSchedule(_options.Schedule, x => x.WithMisfireHandlingInstructionIgnoreMisfires()) .Build(); _scheduler.ScheduleJob(job, trigger); }
public async Task Start() { if (scheduler?.InStandbyMode ?? false) { await scheduler.Start(); } }
protected override void PreStart() { if (!_externallySupplied) { _scheduler.Start(); } base.PreStart(); }
public ScheduleContainer() { var ssf = new StdSchedulerFactory(); Scheduler = ssf.GetScheduler(); Scheduler.Start(); Scheduler.Context.Add("Container", this); }
/// <summary> /// 启动 /// </summary> public async Task StartAsync() { _scheduler = await GetScheduler(); if (_scheduler.IsStarted) { return; } await _scheduler.Start(); }
public virtual void Start() { scheduler.Start(); try { Thread.Sleep(3000); } catch (ThreadInterruptedException) { } logger.Info("Scheduler started successfully"); }
/// <summary> /// 调度任务, /// 根据cron表达式执行 /// </summary> /// <param name="jobDetail">任务明细</param> /// <param name="cron">cron表达式</param> public static void Schedule(IJobDetail jobDetail, string cron) { if (!_Scheduler.CheckExists(jobDetail.Key).Result) { //创建触发器 ITrigger trigger = TriggerBuilder.Create().WithCronSchedule(cron).Build(); //为调度者添加任务与触发器 _Scheduler.ScheduleJob(jobDetail, trigger); //开始调度 _Scheduler.Start(); } else { _Scheduler.ResumeJob(jobDetail.Key); } }
protected void Application_Start() { log4net.Config.XmlConfigurator.Configure(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); JobSchedule JobSchedule = new JobSchedule(); List <ScheduleTask> ScheduleTask = JobSchedule.ScheduleTaskInit(); foreach (var ScheduleTaskItem in ScheduleTask) { if (ScheduleTaskItem.Status == "Enabled") { scheduler.ScheduleJob(ScheduleTaskItem.Job, ScheduleTaskItem.Trigger); } } scheduler.Start(); }
public Scheduler() { this.tirggers = new Dictionary <IScheduledJob, TriggerKey>(); //configuring logger LogProvider.SetCurrentLogProvider(new SchedulerLogProvider()); // Grab the Scheduler instance from the Factory NameValueCollection props = new NameValueCollection { { "quartz.serializer.type", "binary" } }; StdSchedulerFactory factory = new StdSchedulerFactory(props); this.scheduler = factory.GetScheduler().Result; // and start it off scheduler.Start().Wait(); }
public void Start() { Log.Debug("Starting LIM Scheduler"); var properties = new NameValueCollection(); properties["quartz.scheduler.instanceName"] = "RemoteServer"; properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; properties["quartz.threadPool.threadCount"] = "5"; properties["quartz.threadPool.threadPriority"] = "Normal"; properties["quartz.plugin.xml.type"] = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz"; properties["quartz.plugin.xml.fileNames"] = "jobs.xml"; ISchedulerFactory schedulerFactory = new StdSchedulerFactory(properties); _scheduler = schedulerFactory.GetScheduler(); _scheduler.JobFactory = new JobFactory(_container); var bus = _container.Resolve<IAdvancedBus>(); var senderQueue = bus.QueueDeclare("DataPlatform.Integration.Sender"); var senderExchange = bus.ExchangeDeclare("DataPlatform.Integration.Sender", ExchangeType.Fanout); bus.Bind(senderExchange, senderQueue, string.Empty); var receiverQueue = bus.QueueDeclare("DataPlatform.Integration.Receiver"); var receiverExchange = bus.ExchangeDeclare("DataPlatform.Integration.Receiver", ExchangeType.Fanout); bus.Bind(receiverExchange, receiverQueue, string.Empty); bus.Consume(senderQueue, q => q.Add<PackageResponseMessage>( (message, info) => new SenderConsumers<PackageResponseMessage>(message, _container))); bus.Consume(receiverQueue, q => q.Add<PackageConfigurationMessage>( (message, info) => new ReceiverConsumers<PackageConfigurationMessage>(message, _container))); _scheduler.Start(); Log.Debug("LIM Scheduler has started"); }
protected override void OnStart(string[] args) { Tools.Logger.LogToFile(new Models.LogEntry(0, "OnStart", "Service Started Successfully")); // First, initialize Quartz.NET as usual. In this sample app I'll configure Quartz.NET by code. var schedulerFactory = new StdSchedulerFactory(); scheduler = schedulerFactory.GetScheduler(); scheduler.Start(); scheduler.ListenerManager.AddJobListener(new Listeners.GlobalJobListener()); scheduler.ListenerManager.AddTriggerListener(new Listeners.GlobalTriggerListener()); // A sample trigger and job var SoapTrigger = TriggerBuilder.Create() .WithIdentity("CheckTrigger").WithSchedule(Quartz.SimpleScheduleBuilder.RepeatMinutelyForever(2)) .StartNow() .Build(); var SoapJob = new JobDetailImpl("SoapJob", "Soap", typeof(Jobs.SoapJob)); scheduler.ScheduleJob(SoapJob, SoapTrigger); scheduler.AddCalendar("myCalendar", new Calendars.RiskCalendar { Description = "Risk Calendar" }, false, false); }
public async Task <string> Start() { //2、通过调度工厂获得调度器 _scheduler = await _schedulerFactory.GetScheduler(); _scheduler.JobFactory = this._iocJobfactory;// 替换默认工厂 //3、开启调度器 await _scheduler.Start(); //4、创建一个触发器 var trigger = TriggerBuilder.Create() .WithSimpleSchedule(x => x.WithIntervalInSeconds(2).RepeatForever())//每两秒执行一次 .Build(); //5、创建任务 var jobDetail = JobBuilder.Create <OpcServerSyncjob>() .WithIdentity("job", "group") .Build(); //6、将触发器和任务器绑定到调度器中 await _scheduler.ScheduleJob(jobDetail, trigger); return(await Task.FromResult("将触发器和任务器绑定到调度器中完成")); }
public async Task Start(CancellationToken cancellationToken = default) { if (quartzScheduler == null) { var initialized = await InitialiseScheduler(cancellationToken); if (!initialized) { logger.LogError("Failed to initialize scheduler."); return; } } var jobKeys = await quartzScheduler.GetJobKeys(GroupMatcher <JobKey> .AnyGroup()); int allJobs = jobKeys.Count; var triggers = await quartzScheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .AnyGroup()); int activeJobs = triggers.Count; logger.LogInformation($"Configuration loaded, {allJobs} jobs found, {activeJobs} active."); await quartzScheduler.Start(cancellationToken); if (activeJobs == 0) { logger.LogWarning("Scheduler will be started, but has no active jobs!"); } else { logger.LogInformation("Scheduler started."); } if (allJobs > 0) { logger.LogInformation(await GetJobsQuickInfo()); } }
public void Start() { var cronExpression = ConfigurationManager.AppSettings["CronSchedule"]; if (!CronExpression.IsValidExpression(cronExpression)) { _log.Warn("Couldn't start the scheduler. Cron expression is invalid."); return; } if (string.IsNullOrEmpty(cronExpression)) { _log.Warn("No schedule set."); return; } _log.Info("Starting the scheduler..."); _quartzScheduler = _schedulerFactory.GetScheduler(); _quartzScheduler.JobFactory = new NinjectJobFactory(_resolutionRoot); _quartzScheduler.Start(); var job = JobBuilder.Create <PushNotificationJob>() .WithIdentity("job1", "group1") .Build(); var trigger = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartNow() .WithSchedule(CronScheduleBuilder.CronSchedule(cronExpression)) //.WithSimpleSchedule(x => x // .WithIntervalInSeconds(120) // .RepeatForever()) // .ForJob(job) .Build(); _quartzScheduler.ScheduleJob(job, trigger); }
public void Start() { _logger.LogInformation($"Starting Scheduler: {_options.Schedule}"); _scheduler.Start(); var job = JobBuilder.Create <ScheduleExecutor>() .WithIdentity("Job", "TFL") .WithDescription("Scheduled TFL Job") .StoreDurably(false) .RequestRecovery(false) .UsingJobData("Cfg", _options.Arrangement) .UsingJobData("Mode", _options.Mode) .UsingJobData("Schedule", string.Empty) .Build(); var trigger = TriggerBuilder.Create() .WithIdentity("Trigger", "TFL") .StartNow() .WithCronSchedule(_options.Schedule, x => x.WithMisfireHandlingInstructionDoNothing()) .Build(); _scheduler.ScheduleJob(job, trigger); }
public void Start() { Log.Debug("Starting Cache Worker"); var properties = new NameValueCollection(); properties["quartz.scheduler.instanceName"] = "RemoteServer"; properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz"; properties["quartz.threadPool.threadCount"] = "5"; properties["quartz.threadPool.threadPriority"] = "Normal"; properties["quartz.plugin.xml.type"] = "Quartz.Plugin.Xml.XMLSchedulingDataProcessorPlugin, Quartz"; properties["quartz.plugin.xml.fileNames"] = "jobs.xml"; ISchedulerFactory schedulerFactory = new StdSchedulerFactory(properties); _scheduler = schedulerFactory.GetScheduler(); _scheduler.JobFactory = new JobFactory(_container); _scheduler.Start(); _bus = _container.Resolve<IAdvancedBus>(); var receiverQueue = _bus.QueueDeclare("DataPlatform.DataProvider.Cache.Receiver"); var receiverExchange = _bus.ExchangeDeclare("DataPlatform.DataProvider.Cache.Receiver", ExchangeType.Fanout); _bus.Bind(receiverExchange, receiverQueue, string.Empty); _bus.Consume(receiverQueue, q => q .Add<ClearCacheCommand>( (message, info) => new ReceiverConsumers<ClearCacheCommand>(message, _container)) .Add<RefreshCacheCommand>( (message, info) => new ReceiverConsumers<RefreshCacheCommand>(message, _container)) .Add<RestartCacheDataStoreCommand>( (message, info) => new ReceiverConsumers<RestartCacheDataStoreCommand>(message, _container))); Log.Debug("Cache Worker has started"); }
public void Start() { _logger.Info($"Starting Scheduler: {_options.Schedule}"); _scheduler.Start(); foreach (var schedule in _schedule) { if (_options.Mode != "default" && schedule.Mode != _options.Mode) { Console.Error.WriteLine($"Note: The internal schedule's mode of {schedule.Mode} trumps your command line mode of {_options.Mode}."); } _logger.Info($"Schedule {schedule.Name} set for {schedule.Cron} in {schedule.Mode} mode."); var job = JobBuilder.Create <ScheduleExecutor>() .WithIdentity(schedule.Name, "TFL") .WithDescription($"Scheduled TFL Job: {schedule.Name}") .StoreDurably(false) .RequestRecovery(false) .UsingJobData("Cfg", _options.Arrangement) .UsingJobData("Shorthand", _options.Shorthand) .UsingJobData("Mode", schedule.Mode) .UsingJobData("Schedule", schedule.Name) .Build(); var trigger = TriggerBuilder.Create() .WithIdentity(schedule.Name + " Trigger", "TFL") .StartNow() .WithCronSchedule(schedule.Cron, x => x .WithMisfireHandlingInstructionDoNothing() .InTimeZone(schedule.TimeZone == Constants.DefaultSetting ? TimeZoneInfo.Local : TimeZoneInfo.FindSystemTimeZoneById(schedule.TimeZone)) ).Build(); _scheduler.ScheduleJob(job, trigger); } }
public void Start() { _scheduler.Start(); _log.LogInformation <Scheduler>($"Scheduler started. Running jobs every minute."); }
protected override void PreStart() { _scheduler.Start(); base.PreStart(); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { Program.DateOfLastChange_Sequence_Call = new List <DateTime> (); Program.Change_Sequence_Call_Count++; Program.DateOfLastChange_Sequence_Call.Add(DateTime.Now); Program.config_geocode_api_key = ""; Program.config_geocode_api_url = ""; if (!string.IsNullOrEmpty(Configuration["mmria_settings:is_schedule_enabled"])) { bool.TryParse(Configuration["mmria_settings:is_schedule_enabled"], out Program.is_schedule_enabled); } if (!string.IsNullOrEmpty(Configuration["mmria_settings:is_db_check_enabled"])) { bool.TryParse(Configuration["mmria_settings:is_db_check_enabled"], out Program.is_db_check_enabled); } if (!string.IsNullOrEmpty(Configuration["mmria_settings:grantee_name"])) { Program.grantee_name = Configuration["mmria_settings:grantee_name"]; } var test_int = 0; //Program.config_geocode_api_key = configuration["mmria_settings:geocode_api_key"]; //Program.config_geocode_api_url = configuration["mmria_settings:geocode_api_url"]; Program.config_couchdb_url = Configuration["mmria_settings:couchdb_url"]; Program.config_web_site_url = Configuration["mmria_settings:web_site_url"]; //Program.config_file_root_folder = configuration["mmria_settings:file_root_folder"]; Program.config_timer_user_name = Configuration["mmria_settings:timer_user_name"]; Program.config_timer_password = Configuration["mmria_settings:timer_password"]; Program.config_cron_schedule = Configuration["mmria_settings:cron_schedule"]; Program.config_export_directory = Configuration["mmria_settings:export_directory"]; Program.config_session_idle_timeout_minutes = Configuration["mmria_settings:session_idle_timeout"] != null && int.TryParse(Configuration["mmria_settings:session_idle_timeout"], out test_int) ? test_int : 30; Program.config_password_minimum_length = string.IsNullOrWhiteSpace(Configuration["password_settings:minimum_length"])? 8: int.Parse(Configuration["password_settings:minimum_length"]); Program.config_password_days_before_expires = string.IsNullOrWhiteSpace(Configuration["password_settings:days_before_expires"])? 0: int.Parse(Configuration["password_settings:days_before_expires"]); Program.config_password_days_before_user_is_notified_of_expiration = string.IsNullOrWhiteSpace(Configuration["password_settings:days_before_user_is_notified_of_expiration"])? 0: int.Parse(Configuration["password_settings:days_before_user_is_notified_of_expiration"]); /* * Program.config_EMAIL_USE_AUTHENTICATION = Configuration["mmria_settings:EMAIL_USE_AUTHENTICATION"]; * Program.config_EMAIL_USE_SSL = Configuration["mmria_settings:EMAIL_USE_SSL"]; * Program.config_SMTP_HOST = Configuration["mmria_settings:SMTP_HOST"]; * Program.config_SMTP_PORT = Configuration["mmria_settings:SMTP_PORT"]; * Program.config_EMAIL_FROM = Configuration["mmria_settings:EMAIL_FROM"]; * Program.config_EMAIL_PASSWORD = Configuration["mmria_settings:EMAIL_PASSWORD"]; */ Program.config_default_days_in_effective_date_interval = string.IsNullOrWhiteSpace(Configuration["authentication_settings:default_days_in_effective_date_interval"])? 0: int.Parse(Configuration["authentication_settings:default_days_in_effective_date_interval"]); Program.config_unsuccessful_login_attempts_number_before_lockout = string.IsNullOrWhiteSpace(Configuration["authentication_settings:unsuccessful_login_attempts_number_before_lockout"])? 5:int.Parse(Configuration["authentication_settings:unsuccessful_login_attempts_number_before_lockout"]); Program.config_unsuccessful_login_attempts_within_number_of_minutes = string.IsNullOrWhiteSpace(Configuration["authentication_settings:unsuccessful_login_attempts_within_number_of_minutes"])? 120:int.Parse(Configuration["authentication_settings:unsuccessful_login_attempts_within_number_of_minutes"]); Program.config_unsuccessful_login_attempts_lockout_number_of_minutes = string.IsNullOrWhiteSpace(Configuration["authentication_settings:unsuccessful_login_attempts_lockout_number_of_minutes"])? 15:int.Parse(Configuration["authentication_settings:unsuccessful_login_attempts_lockout_number_of_minutes"]); if (bool.Parse(Configuration["mmria_settings:is_environment_based"])) { Log.Information("using Environment"); //Log.Information ("geocode_api_key: {0}", System.Environment.GetEnvironmentVariable ("geocode_api_key")); //Log.Information ("geocode_api_url: {0}", System.Environment.GetEnvironmentVariable ("geocode_api_url")); Log.Information("couchdb_url: {0}", System.Environment.GetEnvironmentVariable("couchdb_url")); Log.Information("web_site_url: {0}", System.Environment.GetEnvironmentVariable("web_site_url")); Log.Information("export_directory: {0}", System.Environment.GetEnvironmentVariable("export_directory")); //Program.config_geocode_api_key = System.Environment.GetEnvironmentVariable ("geocode_api_key"); //Program.config_geocode_api_url = System.Environment.GetEnvironmentVariable ("geocode_api_url"); Program.config_couchdb_url = System.Environment.GetEnvironmentVariable("couchdb_url"); Program.config_web_site_url = System.Environment.GetEnvironmentVariable("web_site_url"); //Program.config_file_root_folder = System.Environment.GetEnvironmentVariable ("file_root_folder"); Program.config_timer_user_name = System.Environment.GetEnvironmentVariable("timer_user_name"); Program.config_timer_password = System.Environment.GetEnvironmentVariable("timer_password"); Program.config_cron_schedule = System.Environment.GetEnvironmentVariable("cron_schedule"); Program.config_export_directory = System.Environment.GetEnvironmentVariable("export_directory") != null?System.Environment.GetEnvironmentVariable("export_directory") : "/workspace/export"; // Program.config_session_idle_timeout_minutes = System.Environment.GetEnvironmentVariable("session_idle_timeout") != null && int.TryParse(System.Environment.GetEnvironmentVariable("session_idle_timeout"), out test_int) ? test_int : 30; Program.config_password_minimum_length = string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("password_minimum_length"))? 8: int.Parse(System.Environment.GetEnvironmentVariable("password_minimum_length")); Program.config_password_days_before_expires = string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("password_days_before_expires"))? 0: int.Parse(System.Environment.GetEnvironmentVariable("password_days_before_expires")); Program.config_password_days_before_user_is_notified_of_expiration = string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("password_days_before_user_is_notified_of_expiration"))? 0: int.Parse(System.Environment.GetEnvironmentVariable("password_days_before_user_is_notified_of_expiration")); if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("sams_endpoint_authorization"))) { Configuration["sams:endpoint_authorization"] = System.Environment.GetEnvironmentVariable("sams_endpoint_authorization"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("sams_endpoint_token"))) { Configuration["sams:endpoint_token"] = System.Environment.GetEnvironmentVariable("sams_endpoint_token"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("sams_endpoint_user_info"))) { Configuration["sams:endpoint_user_info"] = System.Environment.GetEnvironmentVariable("sams_endpoint_user_info"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("sams_endpoint_token_validation"))) { Configuration["sams:token_validation"] = System.Environment.GetEnvironmentVariable("sams_endpoint_token_validation"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("sams_endpoint_user_info_sys"))) { Configuration["sams:user_info_sys"] = System.Environment.GetEnvironmentVariable("sams_endpoint_user_info_sys"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("sams_client_id"))) { Configuration["sams:client_id"] = System.Environment.GetEnvironmentVariable("sams_client_id"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("sams_client_secret"))) { Configuration["sams:client_secret"] = System.Environment.GetEnvironmentVariable("sams_client_secret"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("sams_callback_url"))) { Configuration["sams:callback_url"] = System.Environment.GetEnvironmentVariable("sams_callback_url"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("sams_logout_url"))) { Configuration["sams:logout_url"] = System.Environment.GetEnvironmentVariable("sams_logout_url"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("sams_is_enabled"))) { Configuration["sams:is_enabled"] = System.Environment.GetEnvironmentVariable("sams_is_enabled"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("is_schedule_enabled")) && bool.TryParse(System.Environment.GetEnvironmentVariable("is_schedule_enabled"), out Program.is_schedule_enabled)) { Configuration["is_schedule_enabled"] = System.Environment.GetEnvironmentVariable("is_schedule_enabled"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("is_db_check_enabled")) && bool.TryParse(System.Environment.GetEnvironmentVariable("is_db_check_enabled"), out Program.is_db_check_enabled)) { Configuration["is_db_check_enabled"] = System.Environment.GetEnvironmentVariable("is_db_check_enabled"); } if (!string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("grantee_name"))) { Configuration["grantee_name"] = System.Environment.GetEnvironmentVariable("grantee_name"); Program.grantee_name = Configuration["grantee_name"]; } /* * Program.config_EMAIL_USE_AUTHENTICATION = System.Environment.GetEnvironmentVariable ("EMAIL_USE_AUTHENTICATION"); // = true; * Program.config_EMAIL_USE_SSL = System.Environment.GetEnvironmentVariable ("EMAIL_USE_SSL"); // = true; * Program.config_SMTP_HOST = System.Environment.GetEnvironmentVariable ("SMTP_HOST"); // = null; * Program.config_SMTP_PORT = System.Environment.GetEnvironmentVariable ("SMTP_PORT"); // = 587; * Program.config_EMAIL_FROM = System.Environment.GetEnvironmentVariable ("EMAIL_FROM"); // = null; * Program.config_EMAIL_PASSWORD = System.Environment.GetEnvironmentVariable ("EMAIL_PASSWORD"); // = null; */ Program.config_default_days_in_effective_date_interval = string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("default_days_in_effective_date_interval"))? 90:int.Parse(System.Environment.GetEnvironmentVariable("default_days_in_effective_date_interval")); Program.config_unsuccessful_login_attempts_number_before_lockout = string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("unsuccessful_login_attempts_number_before_lockout"))? 5:int.Parse(System.Environment.GetEnvironmentVariable("unsuccessful_login_attempts_number_before_lockout")); Program.config_unsuccessful_login_attempts_within_number_of_minutes = string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("unsuccessful_login_attempts_within_number_of_minutes"))? 120:int.Parse(System.Environment.GetEnvironmentVariable("unsuccessful_login_attempts_within_number_of_minutes")); Program.config_unsuccessful_login_attempts_lockout_number_of_minutes = string.IsNullOrWhiteSpace(System.Environment.GetEnvironmentVariable("unsuccessful_login_attempts_lockout_number_of_minutes"))? 15:int.Parse(System.Environment.GetEnvironmentVariable("unsuccessful_login_attempts_lockout_number_of_minutes")); } Log.Information($"Program.config_timer_user_name = {Program.config_timer_user_name}"); Log.Information($"Program.config_couchdb_url = {Program.config_couchdb_url}"); Log.Information($"Logging = {Configuration["Logging:IncludeScopes"]}"); Log.Information($"Console = {Configuration["Console:LogLevel:Default"]}"); Log.Information("sams:callback_url: {0}", Configuration["sams:callback_url"]); Log.Information("sams:activity_name: {0}", Configuration["sams:activity_name"]); Log.Information("mmria_settings:is_schedule_enabled: {0}", Configuration["mmria_settings:is_schedule_enabled"]); Log.Information("mmria_settings:is_db_check_enabled: {0}", Configuration["mmria_settings:is_db_check_enabled"]); Program.actorSystem = ActorSystem.Create("mmria-actor-system"); services.AddSingleton(typeof(ActorSystem), (serviceProvider) => Program.actorSystem); ISchedulerFactory schedFact = new StdSchedulerFactory(); Quartz.IScheduler sched = schedFact.GetScheduler().Result; // compute a time that is on the next round minute DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow); // define the job and tie it to our HelloJob class IJobDetail job = JobBuilder.Create <mmria.server.model.Pulse_job>() .WithIdentity("job1", "group1") .Build(); // Trigger the job to run on the next round minute ITrigger trigger = TriggerBuilder.Create() .WithIdentity("trigger1", "group1") .StartAt(runTime.AddMinutes(3)) .WithCronSchedule(Program.config_cron_schedule) .Build(); sched.ScheduleJob(job, trigger); if (Program.is_schedule_enabled) { sched.Start(); } var quartzSupervisor = Program.actorSystem.ActorOf(Props.Create <mmria.server.model.actor.QuartzSupervisor>(), "QuartzSupervisor"); quartzSupervisor.Tell("init"); var use_sams = false; if (!string.IsNullOrWhiteSpace(Configuration["sams:is_enabled"])) { bool.TryParse(Configuration["sams:is_enabled"], out use_sams); } /* * //https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2 * services.AddDistributedMemoryCache(); * services.AddSession(opts => * { * opts.Cookie.HttpOnly = true; * opts.Cookie.Name = ".mmria.session"; * opts.IdleTimeout = TimeSpan.FromMinutes(Program.config_session_idle_timeout_minutes); * }); */ if (use_sams) { if (Configuration["mmria_settings:is_development"] != null && Configuration["mmria_settings:is_development"] == "true") { //https://github.com/jerriepelser-blog/AspnetCoreGitHubAuth/blob/master/AspNetCoreGitHubAuth/ services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.LoginPath = new PathString("/Account/SignIn"); options.AccessDeniedPath = new PathString("/Account/Forbidden/"); options.Cookie.SameSite = SameSiteMode.None; //options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.Events = get_sams_authentication_events(); }); /* * .AddOAuth("SAMS", options => * { * options.ClientId = Configuration["sams:client_id"]; * options.ClientSecret = Configuration["sams:client_secret"]; * options.CallbackPath = new PathString("/Account/SignInCallback");//new PathString(Configuration["sams:callback_url"]);// new PathString("/signin-github"); * * options.AuthorizationEndpoint = Configuration["sams:endpoint_authorization"];// "https://github.com/login/oauth/authorize"; * options.TokenEndpoint = Configuration["sams:endpoint_token"];// ""https://github.com/login/oauth/access_token"; * options.UserInformationEndpoint = Configuration["sams:endpoint_user_info"];// "https://api.github.com/user"; * * options.SaveTokens = true; * * options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id"); * options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name"); * options.ClaimActions.MapJsonKey("urn:github:login", "login"); * options.ClaimActions.MapJsonKey("urn:github:url", "html_url"); * options.ClaimActions.MapJsonKey("urn:github:avatar", "avatar_url"); * * options.Events = new OAuthEvents * { * OnCreatingTicket = async context => * { * var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); * request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); * request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); * * var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted); * response.EnsureSuccessStatusCode(); * * var user = JObject.Parse(await response.Content.ReadAsStringAsync()); * * context.RunClaimActions(user); * } * }; * }); */ } else { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.LoginPath = new PathString("/Account/SignIn"); options.AccessDeniedPath = new PathString("/Account/Forbidden/"); options.Cookie.SameSite = SameSiteMode.None; // options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; options.Events = get_sams_authentication_events(); }); /* * .AddOAuth("SAMS", options => * { * options.ClientId = Configuration["sams:client_id"]; * options.ClientSecret = Configuration["sams:client_secret"]; * options.CallbackPath = Configuration["sams:callback_url"];// new PathString("/signin-github"); * * options.AuthorizationEndpoint = Configuration["sams:endpoint_authorization"];// "https://github.com/login/oauth/authorize"; * options.TokenEndpoint = Configuration["sams:endpoint_token"];// ""https://github.com/login/oauth/access_token"; * options.UserInformationEndpoint = Configuration["sams:endpoint_user_info"];// "https://api.github.com/user"; * * options.SaveTokens = true; * * options.ClaimActions.MapJsonKey(ClaimTypes.NameIdentifier, "id"); * options.ClaimActions.MapJsonKey(ClaimTypes.Name, "name"); * options.ClaimActions.MapJsonKey("urn:github:login", "login"); * options.ClaimActions.MapJsonKey("urn:github:url", "html_url"); * options.ClaimActions.MapJsonKey("urn:github:avatar", "avatar_url"); * * options.Events = new OAuthEvents * { * OnCreatingTicket = async context => * { * var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); * request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); * request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); * * var response = await context.Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.HttpContext.RequestAborted); * response.EnsureSuccessStatusCode(); * * var user = JObject.Parse(await response.Content.ReadAsStringAsync()); * * context.RunClaimActions(user); * } * }; * }); */ } } else { if (Configuration["mmria_settings:is_development"] != null && Configuration["mmria_settings:is_development"] == "true") { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.LoginPath = new PathString("/Account/Login/"); options.AccessDeniedPath = new PathString("/Account/Forbidden/"); options.Cookie.SameSite = SameSiteMode.None; //options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; }); } else { services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options => { options.LoginPath = new PathString("/Account/Login/"); options.AccessDeniedPath = new PathString("/Account/Forbidden/"); options.Cookie.SameSite = SameSiteMode.None; // options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; }); } } services.AddAuthorization(options => { //options.AddPolicy("AdministratorOnly", policy => policy.RequireRole("Administrator")); options.AddPolicy("abstractor", policy => policy.RequireRole("abstractor")); options.AddPolicy("form_designer", policy => policy.RequireRole("form_designer")); options.AddPolicy("committee_member", policy => policy.RequireRole("committee_member")); options.AddPolicy("jurisdiction_admin", policy => policy.RequireRole("jurisdiction_admin")); options.AddPolicy("installation_admin", policy => policy.RequireRole("installation_admin")); options.AddPolicy("guest", policy => policy.RequireRole("guest")); //options.AddPolicy("form_designer", policy => policy.RequireClaim("EmployeeId")); //options.AddPolicy("EmployeeId", policy => policy.RequireClaim("EmployeeId", "123", "456")); //options.AddPolicy("Over21Only", policy => policy.Requirements.Add(new MinimumAgeRequirement(21))); //options.AddPolicy("BuildingEntry", policy => policy.Requirements.Add(new OfficeEntryRequirement())); }); services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }); //https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=netcore-cli // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); this.Start(); }
public void Start() { foreach (var schedule in _schedule) { if (_options.Mode != "default" && schedule.Mode != _options.Mode) { Console.Error.WriteLine($"Note: The internal schedule's mode of {schedule.Mode} trumps your command line mode of {_options.Mode}."); } _logger.LogInformation($"Schedule {schedule.Name} set for {schedule.Cron} in {schedule.Mode} mode."); var job = JobBuilder.Create <ScheduleExecutor>() .WithIdentity(schedule.Name, "TFL") .WithDescription($"Scheduled TFL Job: {schedule.Name}") .StoreDurably(false) .RequestRecovery(false) .UsingJobData("Cfg", _options.Arrangement) .UsingJobData("Mode", schedule.Mode) .UsingJobData("Schedule", schedule.Name) .Build(); ITrigger trigger; switch (schedule.MisFire) { case "ignore": trigger = TriggerBuilder.Create() .WithIdentity(schedule.Name.Titleize() + " Trigger", "TFL") .StartNow() .WithCronSchedule(schedule.Cron, x => x .WithMisfireHandlingInstructionIgnoreMisfires() .InTimeZone(schedule.TimeZone == Constants.DefaultSetting ? TimeZoneInfo.Local : TimeZoneInfo.FindSystemTimeZoneById(schedule.TimeZone)) ).Build(); break; case "fire": case "fireandproceed": trigger = TriggerBuilder.Create() .WithIdentity(schedule.Name.Titleize() + " Trigger", "TFL") .StartNow() .WithCronSchedule(schedule.Cron, x => x .WithMisfireHandlingInstructionFireAndProceed() .InTimeZone(schedule.TimeZone == Constants.DefaultSetting ? TimeZoneInfo.Local : TimeZoneInfo.FindSystemTimeZoneById(schedule.TimeZone)) ).Build(); break; default: trigger = TriggerBuilder.Create() .WithIdentity(schedule.Name.Titleize() + " Trigger", "TFL") .StartNow() .WithCronSchedule(schedule.Cron, x => x .WithMisfireHandlingInstructionDoNothing() .InTimeZone(schedule.TimeZone == Constants.DefaultSetting ? TimeZoneInfo.Local : TimeZoneInfo.FindSystemTimeZoneById(schedule.TimeZone)) ).Build(); break; } _scheduler.ScheduleJob(job, trigger); } _scheduler.Start(); }
private QuartzWrapper() { var schedulerFact = new Quartz.Impl.StdSchedulerFactory(); _scheduler = schedulerFact.GetScheduler(); _scheduler.Start(); }
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 }
protected override void OnStart(string[] args) { //System.Threading.Thread.Sleep(10000); scheduler.Start(); }