コード例 #1
0
        protected virtual void CreateJobCommand(CreateJob createJob)
        {
            if (createJob.To == null)
            {
                Context.Sender.Tell(new CreateJobFail(null, null, new ArgumentNullException(nameof(createJob.To))));
            }
            if (createJob.Trigger == null)
            {
                Context.Sender.Tell(new CreateJobFail(null, null, new ArgumentNullException(nameof(createJob.Trigger))));
            }
            else
            {
                try
                {
                    var job =
                        QuartzJob.CreateBuilderWithData(createJob.To, createJob.Message)
                        .WithIdentity(createJob.Trigger.JobKey)
                        .Build();
                    _scheduler.ScheduleJob(job, createJob.Trigger);

                    Context.Sender.Tell(new JobCreated(createJob.Trigger.JobKey, createJob.Trigger.Key));
                }
                catch (Exception ex)
                {
                    Context.Sender.Tell(new CreateJobFail(createJob.Trigger.JobKey, createJob.Trigger.Key, ex));
                }
            }
        }
コード例 #2
0
        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);
        }
コード例 #3
0
    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);
        }
    }
コード例 #4
0
        private void Schedule(Func <IJobDetail> jobFactory, DateTime runAt, ScheduleKey key)
        {
            try
            {
                _logger.Debug("Scheduling job {Task}", key);
                var job     = jobFactory();
                var trigger = TriggerBuilder.Create()
                              .WithIdentity(job.Key.Name, job.Key.Group)
                              .WithSimpleSchedule(x => x.WithMisfireHandlingInstructionFireNow()
                                                  .WithRepeatCount(0))
                              .StartAt(runAt)
                              .Build();

                var fireTime = _scheduler.ScheduleJob(job, trigger);
                _logger.Debug("Scheduled job {Task} at {Time}", key, fireTime);
                Sender.Tell(new Scheduled(fireTime.UtcDateTime));
            }
            catch (JobPersistenceException e)
            {
                _logger.Error(e, "Error while scheduled job {Task}", key);
                if (e.InnerException?.GetType() == typeof(ObjectAlreadyExistsException))
                {
                    Sender.Tell(new AlreadyScheduled(key));
                }
            }
            catch (Exception e)
            {
                _logger.Error(e, "Error while scheduled job {Task}", key);
                Sender.Tell(new Failure {
                    Exception = e, Timestamp = BusinessDateTime.UtcNow
                });
            }
        }
コード例 #5
0
        public async Task Execute(IJobExecutionContext context)
        {
            _logger.LogInformation("Start JobSchedule!");
            var listSchedule = _context.Test_schedule.Where(p => p.status.ToLower().Equals("running")).ToList();

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

                await _scheduler.AddJob(job, true);

                string[] time    = schedule.job_repeat_time.Split(':');
                ITrigger trigger = TriggerBuilder.Create()
                                   .ForJob(job)
                                   .WithIdentity(schedule.id_schedule + "trigger", schedule.id_user)
                                   .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(int.Parse(time[0]), int.Parse(time[1])))
                                   //.StartNow()
                                   //.WithSimpleSchedule(z => z.WithIntervalInSeconds(10).RepeatForever())
                                   .Build();

                await _scheduler.ScheduleJob(trigger);
            }
        }
コード例 #6
0
ファイル: Scheduler.cs プロジェクト: gbrantzos/Cubes.Core
        private async Task <bool> LoadConfiguration(CancellationToken cancellationToken = default)
        {
            _failedToLoad = true;
            try
            {
                if (!_quartzScheduler.InStandbyMode)
                {
                    throw new InvalidOperationException($"{nameof(LoadConfiguration)} should be called when {nameof(Scheduler)} is stopped.");
                }

                // Load configuration
                var settings = _schedulerConfiguration
                               .GetSection(nameof(SchedulerSettings))
                               .Get <SchedulerSettings>();
                if (settings == null)
                {
                    throw new ArgumentException("Scheduler settings cannot be null!");
                }
                await _quartzScheduler.Clear();

                _internalDetails = new HashSet <SchedulerJobDetails>();

                // Validate settings
                settings.Validate();

                foreach (var job in settings.Jobs)
                {
                    var details = new SchedulerJobDetails
                    {
                        Name              = job.Name,
                        CronExpression    = job.CronExpression,
                        JobInstanceAsJson = job.AsJson()
                    };

                    var quartzJob     = job.GetQuartzJob();
                    var quartzTrigger = job.GetQuartzTrigger();
                    if (job.Active)
                    {
                        await _quartzScheduler.ScheduleJob(quartzJob, quartzTrigger, cancellationToken);
                    }
                    else
                    {
                        await _quartzScheduler.AddJob(quartzJob, true, true, cancellationToken);
                    }

                    details.JobKey         = quartzJob.Key;
                    details.RefireIfMissed = job.RefireIfMissed;
                    _internalDetails.Add(details);
                }

                _failedToLoad = false;
                return(true);
            }
            catch (Exception x)
            {
                _logger.LogError(x, $"Failed to load scheduler settings: {x.Message}");
                return(false);
            }
        }
コード例 #7
0
        public void Queue <T>(T job, int minutes)
        {
            var name = job.GetType().Name;

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity($"{name}_Every{minutes}Minutes", "Group1")
                               .StartNow()
                               .WithSimpleSchedule(x => x
                                                   .WithIntervalInMinutes(minutes)
                                                   .RepeatForever())
                               .Build();

            //note: this breaks if T not IJob type...
            IJobDetail detail = JobBuilder.Create(typeof(T))
                                .WithIdentity($"{name}_Job", "Group1")
                                .Build();

            _scheduler.ScheduleJob(detail, trigger);
        }
コード例 #8
0
ファイル: SchuldeHelper.cs プロジェクト: radtek/ZcSchedule
        /// <summary>
        ///添加一箱
        /// </summary>
        /// <param name="scheduler"></param>
        /// <param name="item"></param>
        private static void addjob(Quartz.IScheduler scheduler, Core.Config item)
        {
            Assembly assembly = Assembly.Load(item.assemblyname);
            Type     type     = assembly.GetType(item.@namespace);


            IJobDetail job = JobBuilder.Create(type)
                             .WithIdentity(item.jobname, item.groupname).Build(); // name "myJob", group "group1"

            var trigger = addTriger(item);



            scheduler.ScheduleJob(job, trigger.Build());
        }
コード例 #9
0
        /// <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);
            }
        }
コード例 #10
0
        public void Queue <T>(T job) where T : IJob
        {
            var name = job.GetType().Name;

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity($"{name}_EveryMinute", "Group1")
                               .StartNow()
                               .WithSimpleSchedule(x => x
                                                   .WithIntervalInMinutes(1)
                                                   .RepeatForever())
                               .Build();

            IJobDetail detail = JobBuilder.Create <T>()
                                .WithIdentity($"{name}_Job", "Group1")
                                .Build();

            _scheduler.ScheduleJob(detail, trigger);
        }
コード例 #11
0
ファイル: Global.asax.cs プロジェクト: Sadtime200/Kerry.KSYS
        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();
        }
コード例 #12
0
ファイル: Spec.cs プロジェクト: csuffyy/GridDomain
        public void Legacy_wire_data_can_run_with_latest_job_code()
        {
            ScheduleKey      key              = new ScheduleKey(Guid.NewGuid(), Name, Group);
            Command          command          = new SuccessCommand("1232");
            ExecutionOptions executionOptions = new ExecutionOptions(DateTime.Now.AddSeconds(1), typeof(ScheduledCommandSuccessfullyProcessed));

            var serializedCommand = SerializeAsLegacy(command);
            var serializedKey     = SerializeAsLegacy(key);
            var serializedOptions = SerializeAsLegacy(executionOptions);

            var jobDataMap = new JobDataMap
            {
                { QuartzJob.CommandKey, serializedCommand },
                { QuartzJob.ScheduleKey, serializedKey },
                { QuartzJob.ExecutionOptionsKey, serializedOptions }
            };

            var legacyJob = QuartzJob.CreateJob(key, jobDataMap);

            var listener = new CallbackJobListener();

            _quartzScheduler.ListenerManager.AddJobListener(listener, KeyMatcher <JobKey> .KeyEquals(legacyJob.Key));
            var task = listener.TaskFinish.Task;

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(legacyJob.Key.Name, legacyJob.Key.Group)
                          .WithSimpleSchedule(x => x.WithMisfireHandlingInstructionFireNow()
                                              .WithRepeatCount(0))
                          .StartAt(DateTimeOffset.Now.AddMilliseconds(200))
                          .Build();

            _quartzScheduler.ScheduleJob(legacyJob, trigger);

            if (!task.Wait(TimeSpan.FromSeconds(10000)))
            {
                Assert.Fail("Job execution timed out");
            }

            if (task.Result.Item2 != null)
            {
                Assert.Fail("Job threw an exception", task.Result.Item2);
            }
        }
コード例 #13
0
 public bool StartJob(string jobName, IJobExecutor handler, string cron)
 {
     lock (joblocker)
     {
         var existjob = Jobs.Exists(x => x.JobName == jobName);
         if (existjob)
         {
             return(false);
         }
         //string InnerJobId = Guid.NewGuid().ToString();
         JobDetailImpl jobdetail = new JobDetailImpl(jobName, typeof(RuanalInnerJob));
         jobdetail.Description = "内部调度任务";
         Quartz.ITrigger triger    = null;
         var             isrunonce = cron.ToLower() == "runonce";
         if (isrunonce)
         {
             var ttriger = new Quartz.Impl.Triggers.SimpleTriggerImpl("trigger_" + jobName);
             ttriger.RepeatCount    = 0;
             ttriger.RepeatInterval = TimeSpan.FromSeconds(1);
             triger = ttriger;
         }
         else
         {
             var ttriger = new Quartz.Impl.Triggers.CronTriggerImpl("trigger_" + jobName);
             ttriger.CronExpressionString = cron;
             triger = ttriger;
         }
         JobContext jobitem = new JobContext()
         {
             //  InnerJobId = InnerJobId,
             IsRunOnce   = isrunonce,
             JobName     = jobName,
             JobDetail   = jobdetail,
             LastRunTime = null,
             OnInvoke    = handler
         };
         jobitem.Triggers.Add(triger);
         Jobs.Add(jobitem);
         Scheduler.ScheduleJob(jobdetail, triger);
         return(true);
     }
 }
コード例 #14
0
        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);
        }
コード例 #15
0
ファイル: QuartzStartup.cs プロジェクト: lvjiajun/HubRestful
        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("将触发器和任务器绑定到调度器中完成"));
        }
コード例 #16
0
        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);
        }
コード例 #17
0
        private async Task <bool> TrySetSchedule(string cronExpression, Quartz.IScheduler scheduler)
        {
            if (!CronExpression.IsValidExpression(cronExpression))
            {
                return(false);
            }

            IJobDetail job = JobBuilder.Create <PostWeeklySeedJob>()
                             .WithIdentity("WeeklySeedJob", "Group1")
                             .Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("schedule", "Group1")
                               .StartNow()
                               .WithCronSchedule(cronExpression)
                               .Build();

            await scheduler.Clear();

            await scheduler.ScheduleJob(job, trigger);

            return(true);
        }
        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);
        }
コード例 #19
0
        private async Task Schedule(ScheduleCommandExecution message)
        {
            ScheduleKey key = message.Key;

            try
            {
                _logger.Debug($"Scheduling job {key} for {message.Options.RunAt}");
                var job     = QuartzJob.Create(message.Key, message.Command, message.CommandMetadata, message.Options);
                var trigger =
                    TriggerBuilder.Create()
                    .WithIdentity(job.Key.Name, job.Key.Group)
                    .WithSimpleSchedule(x => x.WithMisfireHandlingInstructionFireNow().WithRepeatCount(0))
                    .StartAt(message.Options.RunAt)
                    .Build();

                var fireTime = await _scheduler.ScheduleJob(job, trigger);

                var scheduleConfirmation = new CommandExecutionScheduled(message.Command.Id, fireTime.UtcDateTime);
                Sender.Tell(scheduleConfirmation);
                _publisher.Publish(scheduleConfirmation, message.CommandMetadata);
            }
            catch (Exception e)
            {
                _logger.Error(e, "Error while scheduled job {Task}", key);
                if (e is JobPersistenceException && e.InnerException?.GetType() == typeof(ObjectAlreadyExistsException))
                {
                    Sender.Tell(new AlreadyScheduled(key));
                }
                else
                {
                    Sender.Tell(new Status.Failure(e));
                }

                var fault = Fault.New(message, e, message.Command.ProcessId, typeof(SchedulingActor));
                _publisher.Publish(fault, message.CommandMetadata);
            }
        }
コード例 #20
0
        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);
            }
        }
コード例 #21
0
        public async Task ScheduleAction(PubSubProxyActor.SubToTime sub)
        {
            var jobData = new JobDataMap((IDictionary <string, object>) new Dictionary <string, object>
            {
                { TellScheduleJob.JobDataActor, sub.Subscriber }
            });

            var jobName     = sub.GetJobName();
            var triggerName = sub.GetTriggerName();
            var cron        = sub.Cron;

            var job = JobBuilder.Create <TellScheduleJob>()
                      .WithIdentity(jobName)
                      .SetJobData(jobData)
                      .Build();

            var trigger = TriggerBuilder.Create()
                          .WithIdentity(triggerName)
                          .WithCronSchedule(cron)
                          .Build();

            _logger?.LogInformation($"Schedule tell to '{sub.Subscriber.Path.Name}' {CronExpressionDescriptor.ExpressionDescriptor.GetDescription(sub.Cron)}");
            await _quartzScheduler.ScheduleJob(job, trigger);
        }
コード例 #22
0
        // 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();
        }
コード例 #23
0
        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();
        }
コード例 #24
0
        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
        }
コード例 #25
0
        /// <summary>
        /// 添加作业
        /// </summary>
        /// <param name="job">作业</param>
        /// <param name="trigger">触发器</param>
        public async Task AddJobAsync(IJobDetail job, ITrigger trigger)
        {
            _scheduler = await GetScheduler();

            await _scheduler.ScheduleJob(job, trigger);
        }
コード例 #26
0
        public async Task <IActionResult> Add(AddSpiderViewModel dto)
        {
            if (!ModelState.IsValid)
            {
                return(View("Add", dto));
            }

            var exists = await _dbContext.Spiders.AnyAsync(x =>
                                                           x.Name == dto.Name);

            if (exists)
            {
                ModelState.AddModelError("Name", "名称已经存在");
            }

            var imageExists = await _dbContext.DockerImages.AnyAsync(x => x.Image == dto.Image);

            if (!imageExists)
            {
                ModelState.AddModelError("Image", "镜像不存在");
            }

            try
            {
                TriggerBuilder.Create().WithCronSchedule(dto.Cron).Build();
            }
            catch
            {
                ModelState.AddModelError("Cron", "CRON 表达式不正确");
            }

            if (ModelState.IsValid)
            {
                var transaction = await _dbContext.Database.BeginTransactionAsync();

                try
                {
                    var spider = new Portal.Entity.Spider
                    {
                        Name                 = dto.Name,
                        Cron                 = dto.Cron,
                        Image                = dto.Image,
                        Environment          = dto.Environment,
                        CreationTime         = DateTime.Now,
                        LastModificationTime = DateTime.Now
                    };
                    _dbContext.Spiders.Add(spider);
                    await _dbContext.SaveChangesAsync();

                    var id      = spider.Id.ToString();
                    var trigger = TriggerBuilder.Create().WithCronSchedule(dto.Cron).WithIdentity(id).Build();
                    var qzJob   = JobBuilder.Create <TriggerJob>().WithIdentity(id).WithDescription(spider.Name)
                                  .RequestRecovery(true)
                                  .Build();
                    await _sched.ScheduleJob(qzJob, trigger);

                    transaction.Commit();
                }
                catch (Exception e)
                {
                    _logger.LogError($"添加任务失败: {e}");
                    try
                    {
                        transaction.Rollback();
                    }
                    catch (Exception re)
                    {
                        _logger.LogError($"回滚添加任务失败: {re}");
                    }

                    ModelState.AddModelError(string.Empty, "添加任务失败");
                    return(View("Add", dto));
                }

                return(Redirect("/spider"));
            }
            else
            {
                return(View("Add", dto));
            }
        }