private void ScheduleJob()
        {
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTime.Now);

            // construct a scheduler factory
            ISchedulerFactory schedFact = new StdSchedulerFactory();

            // get a scheduler
            IScheduler sched = schedFact.GetScheduler();

            sched.Start();

            JobDataMap jobDataMap = new JobDataMap();

            IJobDetail websitePingJobDetail = JobBuilder.Create <PingJob>()
                                              .WithIdentity("WebsitePingJob", "group1")
                                              .WithDescription("Website Ping Job")
                                              .UsingJobData(jobDataMap)
                                              .Build();

            ITrigger websitePingJobTrigger = TriggerBuilder.Create()
                                             .WithIdentity("WebsitePingJob", "group1")
                                             .StartAt(runTime)
                                             .WithCronSchedule(RoleEnvironment.GetConfigurationSettingValue("PingJobCronSchedule"))
                                             .StartNow()
                                             .Build();

            sched.ScheduleJob(websitePingJobDetail, websitePingJobTrigger);
        }
Beispiel #2
0
        /// <summary>
        /// 数据库同步
        /// </summary>
        public static void StartOAuthsEmpUpDate()
        {
            // start up scheduler
            // construct a factory
            ISchedulerFactory factory = new StdSchedulerFactory();

            // get a scheduler
            scheduler = factory.GetScheduler();
            // start the scheduler
            scheduler.Start();

            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow.AddDays(-1));

            // create job
            IJobDetail job = JobBuilder.Create <HandleOAuthsEmpUpDate>()
                             .WithIdentity("JosonJiang", "JosonJiang")
                             .Build();

            // create trigger
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("JosonJiangJobTrigger", "JosonJiangJobs")
                               // start at 7:30 every day
                               //.StartAt(DateBuilder.DateOf(7, 30, 0))
                               .StartAt(runTime)
                               .WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromMilliseconds(1)).WithRepeatCount(0))

                               .Build();

            // Schedule the job using the job and trigger
            scheduler.ScheduleJob(job, trigger);
        }
Beispiel #3
0
        public void StartTrigger()
        {
            // construct a scheduler factory
            ISchedulerFactory schedFact = new StdSchedulerFactory();

            // get a scheduler
            _sched = schedFact.GetScheduler().Result;

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create <QuartzJob>()
                             .WithIdentity("job_" + datasetConfig.Name, "group1")
                             .Build();


            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            // Trigger the job to run on the next round minute
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger_" + datasetConfig.Name, "group1")
                               .WithCronSchedule(datasetConfig.CronTab)
                               //.StartAt(runTime)
                               .Build();

            job.JobDataMap["CallbackMethod"] = new Action(TriggerCallback);

            _sched.ScheduleJob(job, trigger);
            _sched.Start();
        }
Beispiel #4
0
        public void Run()
        {
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            int num = 0;

            if (Jobs != null && Jobs.Any())
            {
                foreach (var job in Jobs)
                {
                    num++;

                    var detail = JobBuilder.Create(job.GetType())
                                 .WithIdentity("Job" + num, "Group" + num)
                                 .RequestRecovery()
                                 .Build();

                    var trigger = TriggerBuilder.Create()
                                  .WithIdentity("Trigger" + num, "Group" + num)
                                  .StartAt(runTime)
                                  .WithSimpleSchedule(x => x.WithIntervalInSeconds(job.Interval > 0 ? job.Interval : 60).RepeatForever())
                                  .Build();

                    sched.ScheduleJob(detail, trigger);
                }
            }
            sched.Start();
        }
Beispiel #5
0
        public virtual async Task Run()
        {
            ILog log = LogProvider.GetLogger(typeof(SimpleExample));

            log.Info("------- Initializing ----------------------");

            // First we must get a reference to a scheduler
            var properties = new NameValueCollection
            {
                ["quartz.serializer.type"] = "json"
            };
            ISchedulerFactory sf    = new StdSchedulerFactory(properties);
            IScheduler        sched = await sf.GetScheduler();

            log.Info("------- Initialization Complete -----------");


            // computer a time that is on the next round minute
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            log.Info("------- Scheduling Job  -------------------");

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create <HelloJob>()
                             .WithIdentity("job1", "group1")
                             .Build();

            // Trigger the job to run on the next round minute
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1")
                               .StartAt(runTime)
                               .Build();

            // Tell quartz to schedule the job using our trigger
            await sched.ScheduleJob(job, trigger);

            log.Info($"{job.Key} will run at: {runTime.ToString("r")}");

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            await sched.Start();

            log.Info("------- Started Scheduler -----------------");

            // wait long enough so that the scheduler as an opportunity to
            // run the job!
            log.Info("------- Waiting 65 seconds... -------------");

            // wait 65 seconds to show jobs
            await Task.Delay(TimeSpan.FromSeconds(65));

            // shut down the scheduler
            log.Info("------- Shutting Down ---------------------");
            await sched.Shutdown(true);

            log.Info("------- Shutdown Complete -----------------");
        }
Beispiel #6
0
        static void Main(string[] args)
        {
            string rabbitMQBrokerHost = "localhost";
            string virtualHost        = "machine";
            string username           = "******";
            string password           = "******";

            string connectionString = string.Format(
                "host={0};virtualHost={1};username={2};password={3}",
                rabbitMQBrokerHost, virtualHost, username, password);

            using (IAdvancedBus bus = RabbitHutch.CreateBus(connectionString).Advanced)
            {
                IExchange exchange = bus.ExchangeDeclare("machine", EasyNetQ.Topology.ExchangeType.Fanout);
                IAdvancedPublishChannel boxPublishChannel = bus.OpenPublishChannel();
                MachineInfo             machineInfo       = new MachineInfo();

                var jobDataMap = new JobDataMap();
                jobDataMap.Add("username", username);
                jobDataMap.Add("IAdvancedBus", bus);
                jobDataMap.Add("IExchange", exchange);
                jobDataMap.Add("IAdvancedPublishChannel", boxPublishChannel);
                jobDataMap.Add("MachineInfo", machineInfo);

                ISchedulerFactory sf    = new StdSchedulerFactory();
                IScheduler        sched = sf.GetScheduler();

                // computer a time that is on the next round minute
                DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

                IJobDetail job = JobBuilder.Create <MachineMonitorJob>()
                                 .UsingJobData(jobDataMap)
                                 .Build();

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("trigger1", "group1")
                                   .StartNow()
                                   .WithSimpleSchedule(
                    x => x.WithInterval(TimeSpan.FromMilliseconds(1000)).RepeatForever())
                                   .Build();

                // Tell quartz to schedule the job using our trigger
                sched.ScheduleJob(job, trigger);

                // Start up the scheduler (nothing can actually run until the
                // scheduler has been started)
                sched.Start();

                Console.WriteLine("Press any key to quit.");
                Console.ReadLine();

                sched.Shutdown(true);
            }
        }
Beispiel #7
0
        public override ITrigger CreateTrigger()
        {
            var startTime = DateBuilder.EvenMinuteDate(DateTime.Now);

            ITrigger trigger = TriggerBuilder.Create()
                               .WithSimpleSchedule(x => x.WithInterval(new TimeSpan(this.Days, this.Hours, this.Minutes, this.Seconds)).RepeatForever())
                               .StartAt(startTime)
                               .Build();

            return(trigger);
        }
Beispiel #8
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(HelloRun));

            log.Info("------- Initializing ----------------------");

            // First we must get a reference to a scheduler
            //ISchedulerFactory sf = new StdSchedulerFactory();
            //IScheduler sched = sf.GetScheduler();
            IQuartzServer server = QuartzServerFactory.CreateServer();

            server.Initialize();
            IScheduler sched = server.GetScheduler();

            log.Info("------- Initialization Complete -----------");


            // computer a time that is on the next round minute
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            log.Info("------- Scheduling Job  -------------------");

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create <HelloJob>()
                             .WithIdentity("job1", "group1")
                             .Build();

            // Trigger the job to run on the next round minute
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1")
                               .StartAt(runTime)
                               .Build();

            // Tell quartz to schedule the job using our trigger
            sched.ScheduleJob(job, trigger);
            log.Info(string.Format("{0} will run at: {1}", job.Key, runTime.ToString("r")));

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            sched.Start();
            log.Info("------- Started Scheduler -----------------");

            // wait long enough so that the scheduler as an opportunity to
            // run the job!
            log.Info("------- Waiting 65 seconds... -------------");

            // wait 65 seconds to show jobs
            Thread.Sleep(TimeSpan.FromSeconds(65));

            // shut down the scheduler
            log.Info("------- Shutting Down ---------------------");
            sched.Shutdown(true);
            log.Info("------- Shutdown Complete -----------------");
        }
Beispiel #9
0
        /// <summary>
        /// 任务调用的方法
        /// </summary>
        public void Execute(IJobExecutionContext context)
        {
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            int  rowsAffected = 0;
            bool isSucessful  = false;

            Net.DBUtility.DbHelperSQL.RunProcedure("CreateMessagesQueues", out rowsAffected);

            isSucessful = rowsAffected > -1;

            Console.WriteLine(isSucessful + "CreateMessagesQueues, JosonJiang  -- start at 0:00   !" + runTime);
        }
        public virtual async Task Run()
        {
            Console.WriteLine("------- Initializing ----------------------");

            // First we must get a reference to a scheduler
            ISchedulerFactory sf    = new StdSchedulerFactory();
            IScheduler        sched = await sf.GetScheduler();

            Console.WriteLine("------- Initialization Complete -----------");


            // computer a time that is on the next round minute
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            Console.WriteLine("------- Scheduling Job  -------------------");

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create <HelloJob>()
                             .WithIdentity("job1", "group1")
                             .Build();

            // Trigger the job to run on the next round minute
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1")
                               .StartAt(runTime)
                               .Build();

            // Tell quartz to schedule the job using our trigger
            await sched.ScheduleJob(job, trigger);

            Console.WriteLine($"{job.Key} will run at: {runTime:r}");

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            await sched.Start();

            Console.WriteLine("------- Started Scheduler -----------------");

            // wait long enough so that the scheduler as an opportunity to
            // run the job!
            Console.WriteLine("------- Waiting 65 seconds... -------------");

            // wait 65 seconds to show jobs
            await Task.Delay(TimeSpan.FromSeconds(65));

            // shut down the scheduler
            Console.WriteLine("------- Shutting Down ---------------------");
            await sched.Shutdown(true);

            Console.WriteLine("------- Shutdown Complete -----------------");
        }
        internal IScheduler StartJobScheduler()
        {
            Logger.Info("------- Initializing ----------------------");
            var stdSchedulerFactory = new StdSchedulerFactory();
            var scheduler           = stdSchedulerFactory.GetScheduler();

            Logger.Info("------- Initialization Complete -----------");

            var runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            Logger.Info("------- Scheduling Email Reminder Job  -------------------");
            var job = JobBuilder.Create <EmailReminderJob>().WithIdentity("emailReminderJob", "group1").Build();

            ITrigger     trigger;
            const string triggerName  = "dailyTrigger";
            const string triggerGroup = "group1";

#if DEBUG
            trigger = TriggerBuilder.Create().WithIdentity(triggerName, triggerGroup).StartAt(runTime).WithSimpleSchedule(s => s.WithIntervalInMinutes(1).RepeatForever()).Build();
#else
            var triggerSimpleSchedulerIntervalInSeconds = ConfigurationManager.AppSettings["TriggerSimpleSchedulerIntervalInSeconds"];
            if (string.IsNullOrWhiteSpace(triggerSimpleSchedulerIntervalInSeconds))
            {
                var triggerCronSchedulerExpression = ConfigurationManager.AppSettings["TriggerCronSchedulerExpression"];
                trigger = TriggerBuilder.Create().WithIdentity(triggerName, triggerGroup).WithCronSchedule(triggerCronSchedulerExpression).Build();
            }
            else
            {
                int repeatInterval;
                if (!int.TryParse(triggerSimpleSchedulerIntervalInSeconds, out repeatInterval))
                {
                    repeatInterval = 60 * 5; //default to 5 minutes
                }
                trigger =
                    TriggerBuilder.Create()
                    .WithIdentity(triggerName, triggerGroup)
                    .StartAt(runTime)
                    .WithSimpleSchedule(s => s.WithIntervalInSeconds(repeatInterval).RepeatForever())
                    .Build();
            }
#endif
            scheduler.ScheduleJob(job, trigger);
            Logger.Info("{0} will run at: {1}", job.Key, runTime.ToString("r"));

            scheduler.Start();
            Logger.Info("------- Started Scheduler -----------------");

            return(scheduler);
        }
Beispiel #12
0
        static void Main(string[] args)
        {
            Stock stock = new Stock();

            stock.priceUpdateEventHandler += stock_priceUpdateEventHandler;
            //stock.PriceChange();
            stock.Price = 10;
            stock.Price = 20;

            Console.ReadLine();

            //DemoDBContext dbContext = new DemoDBContext();
            //var person = new Person()
            //{
            //    ID = Guid.NewGuid().ToString(),
            //    UserName = "******"
            //};
            //dbContext.Person.Add(person);
            //dbContext.SaveChanges();

            ISchedulerFactory factory   = new StdSchedulerFactory();
            IScheduler        scheduler = factory.GetScheduler();

            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            runTime = new DateTimeOffset(DateTime.Now.AddSeconds(60));

            IJobDetail job = JobBuilder.Create <JobDemo>()
                             .WithIdentity("job1", "group1")
                             .Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("job1", "group1")
                               .StartAt(runTime)
                               .Build();

            scheduler.ScheduleJob(job, trigger);

            scheduler.Start();

            System.Threading.Thread.Sleep(1000);

            scheduler.Shutdown();

            Console.WriteLine("end");
            Console.ReadLine();
        }
        // Init the scheduler
        private async Task InitJobSchedulerAsync()
        {
            if (_sched != null)
            {
                return;
            }

            //Quartz.Logging.LogContext.SetCurrentLogProvider(SimpleLogger.Factory);

            // First we must get a reference to a scheduler
            ISchedulerFactory sf = new StdSchedulerFactory();

            _sched = await sf.GetScheduler();

            _sched.Context.Add("cs", this);

            // computer a time that is on the next round minute
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            // define the jobs
            var jobGroup = "consensus service jobs";

            // Tell quartz to schedule the job using our trigger
            await CreateJobAsync(TimeSpan.FromSeconds(24), typeof(HeartBeater), "Heart Beat", jobGroup);
            await CreateJobAsync(TimeSpan.FromMilliseconds(1000), typeof(BlockAuthorizationMonitor), "Block Monitor", jobGroup);
            await CreateJobAsync("0/2 * * * * ?", typeof(LeaderTaskMonitor), "Leader Monitor", jobGroup);
            await CreateJobAsync(TimeSpan.FromMinutes(17), typeof(IdleWorks), "Idle Works", jobGroup);

            // 10 min view change, 30 min fetch balance.
            //if (Neo.Settings.Default.LyraNode.Lyra.NetworkId == "devnet")
            //{
            //    // need a quick debug test
            //    await CreateJobAsync("0 0/2 * * * ?", typeof(NewPlayerMonitor), "Player Monitor", jobGroup);
            //    await CreateJobAsync(TimeSpan.FromMinutes(5), typeof(FetchBalance), "Fetch Balance", jobGroup);
            //}
            //else
            //{
            await CreateJobAsync("0 0/10 * * * ?", typeof(NewPlayerMonitor), "Player Monitor", jobGroup);
            await CreateJobAsync(TimeSpan.FromHours(12), typeof(FetchBalance), "Fetch Balance", jobGroup);

            //}

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            await _sched.Start();
        }
 private void InitializeQuartz()
 {
     ISchedulerFactory sf = new StdSchedulerFactory();
     IScheduler sched = sf.GetScheduler();
     DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTime.UtcNow);
     DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 5);
     IJobDetail job = JobBuilder.Create<QueueConsumer>()
         .WithIdentity("job1", "group1")
         .Build();
     ITrigger trigger = TriggerBuilder.Create()
         .WithIdentity("trigger1", "group1")
         .StartAt(runTime)
         .WithCronSchedule("5 0/1 * * * ?")
         .Build();
     sched.ScheduleJob(job, trigger);
     sched.Start();
 }
Beispiel #15
0
    public MainForm()
    {
        InitializeComponent();
        ISchedulerFactory sf        = new StdSchedulerFactory();
        IScheduler        sched     = sf.GetScheduler();
        DateTimeOffset    runTime   = DateBuilder.EvenMinuteDate(DateTime.UtcNow);
        DateTimeOffset    startTime = DateBuilder.NextGivenSecondDate(null, 10);

        job = JobBuilder.Create <HelloJob>()
              .WithIdentity("job1", "group1")
              .Build();
        ITrigger trigger = TriggerBuilder.Create()
                           .WithIdentity("trigger1", "group1")
                           .StartAt(runTime)
                           .WithCronSchedule("5 0/1 * * * ?")
                           .Build();

        sched.ScheduleJob(job, trigger);
    }
Beispiel #16
0
        /// <summary>
        /// 任务调用的方法
        /// </summary>
        public void Execute(IJobExecutionContext context)
        {
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            int  rowsAffected = 0;
            bool isSucessful  = false;

            System.Data.IDataParameter[] DataParmameter = { new SqlParameter("@Task", "Task"), new SqlParameter("@RunAt", "RunAt") };
            SqlParameter[] parameters = { new SqlParameter("@Task", "Task"), new SqlParameter("@RunAt", "RunAt") };

            Net.DBUtility.DbHelperSQL.RunProcedure("CreateMessagesQueues", out rowsAffected);

            Net.DBUtility.DbHelperSQL.RunProcedure("OAuthsEmpUpDate", parameters, out rowsAffected);
            Console.WriteLine((rowsAffected > -1) + "同步通讯录, JosonJiang  -- !" + runTime);

            Net.DBUtility.DbHelperSQL.RunProcedure("AddressBooksUpDate", DataParmameter, out rowsAffected);
            isSucessful = rowsAffected > -1;

            Console.WriteLine(isSucessful + "同步通讯录, JosonJiang  -- start at 7:30 every day 执行1次 !" + runTime);
        }
Beispiel #17
0
        protected void ScheduleJobWithDefaultTrigger <T>(string jobGroupName, string jobName) where T : IJob
        {
            JobBuilder builder = JobBuilder.Create <T>()
                                 .WithIdentity(jobName, jobGroupName)
                                 .WithDescription(jobGroupName + "." + jobName);

            IJobDetail job = builder.Build();

            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity(TriggerName, jobGroupName)
                               .StartAt(runTime)
                               .WithSchedule(CalendarIntervalScheduleBuilder.Create().WithIntervalInMinutes(1))
                               .Build();

            _sched.ScheduleJob(job, trigger);

            Context = new SchedulerModel(_sched);
        }
Beispiel #18
0
        public void Execute(IJobExecutionContext context)
        {
            _logger.InfoFormat("同步通讯录");

            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            int  flag        = 0;
            bool isSucessful = false;

            System.Data.IDataParameter[] DataParmameter = { new SqlParameter("@Task", "Task"), new SqlParameter("@RunAt", "RunAt") };

            SqlParameter[] parameters = { new SqlParameter("@Task", "Task"), new SqlParameter("@RunAt", "RunAt") };


            Net.DBUtility.DbHelperSQL.RunProcedure("OAuthsEmpUpDate", parameters, out flag);
            Net.DBUtility.DbHelperSQL.RunProcedure("AddressBooksUpDate", DataParmameter, out flag);

            isSucessful = flag == -1;

            Console.WriteLine(isSucessful + "同步通讯录, JosonJiang  -- start at 7:30 every day 执行1次 !" + runTime);
        }
Beispiel #19
0
        public void CreateContext()
        {
            JobBuilder builder = JobBuilder.Create <T>()
                                 .WithIdentity(JobName, GroupName)
                                 .WithDescription(JobDescription);

            CustomizeJob(builder);

            IJobDetail job = builder.Build();

            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity(TriggerName, GroupName)
                               .StartAt(runTime)
                               .WithSchedule(CalendarIntervalScheduleBuilder.Create().WithIntervalInMinutes(1))
                               .Build();

            _sched.ScheduleJob(job, trigger);

            Context = new JobModel(_sched, new JobKey(JobName, GroupName));
        }
Beispiel #20
0
        public void SetUp()
        {
            _now     = DateTimeOffset.UtcNow;
            _runTime = DateBuilder.EvenMinuteDate(_now);
            _jobData = new Dictionary <string, object> {
                { "object1", new { PropertyValue = 3 } }
            };
            _jobDataMap = new JobDataMap(_jobData);
            _endTime    = DateTime.UtcNow.AddMonths(1);

            _trigger = TriggerBuilder.Create()
                       .WithIdentity(TriggerName, GroupName)
                       .WithDescription(Description)
                       .StartAt(_runTime)
                       .WithPriority(Priority)
                       .WithSchedule(CalendarIntervalScheduleBuilder.Create().WithIntervalInMinutes(1))
                       .UsingJobData(_jobDataMap)
                       .EndAt(_endTime)
                       .Build();

            _context = new TriggerModel(_trigger);
        }
Beispiel #21
0
        public void StartJobs()
        {
            try {
                _log = LogManager.GetLogger(typeof(JobManager));

                _log.Info("------- Initializing ----------------------");

                DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

                var jobs = GetJobs();

                foreach (var job in jobs)
                {
                    _scheduler = _sf.GetScheduler();

                    _log.Info("------- Initialization Complete -----------");

                    IJobDetail jobDetail = new JobDetailImpl(job.Name(), GroupName, job.GetType());

                    var trigger =
                        (ICronTrigger)TriggerBuilder.Create()
                        .WithIdentity(job.Name() + "Trigger", GroupName)
                        .WithCronSchedule(job.Cron())
                        .Build();

                    _scheduler.ScheduleJob(jobDetail, trigger);
                    _log.Info(string.Format("{0} will run at: {1}", jobDetail.Key, runTime.ToString("r")));
                }
                _scheduler.JobFactory = _jobFactory;
                _scheduler.Start();

                _log.Info("------- Started Scheduler -----------------");
            } catch (Exception e) {
                _log.Error("error starting jobs", e);
                throw;
            }
        }
Beispiel #22
0
        // Init the scheduler
        public async Task InitJobSchedulerAsync()
        {
            if (_sched != null)
            {
                return;
            }

            //Quartz.Logging.LogContext.SetCurrentLogProvider(SimpleLogger.Factory);

            // First we must get a reference to a scheduler
            ISchedulerFactory sf = new StdSchedulerFactory();

            _sched = await sf.GetScheduler();

            _sched.Context.Add("ic", this);

            // computer a time that is on the next round minute
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            // define the jobs
            var jobGroup = "inc jobs";

            // Tell quartz to schedule the job using our trigger
            await CreateJobAsync(TimeSpan.FromMinutes(5), typeof(PayNodes), "Pay staking nodes", jobGroup);

            //await CreateJobAsync(TimeSpan.FromMilliseconds(100), typeof(BlockAuthorizationMonitor), "Block Monitor", jobGroup);
            //await CreateJobAsync("0/2 * * * * ?", typeof(LeaderTaskMonitor), "Leader Monitor", jobGroup);

            //// 10 min view change, 30 min fetch balance.
            //await CreateJobAsync("0 0/10 * * * ?", typeof(NewPlayerMonitor), "Player Monitor", jobGroup);
            //await CreateJobAsync(TimeSpan.FromMinutes(30), typeof(FetchBalance), "Fetch Balance", jobGroup);

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            await _sched.Start();
        }
Beispiel #23
0
        public async Task Text()
        {
            //获取一个定时器管理者
            ISchedulerFactory sf    = new StdSchedulerFactory();
            IScheduler        sched = await sf.GetScheduler();

            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);

            IJobDetail job = JobBuilder.Create <HelloJob>()
                             .WithIdentity("job1", "group1")
                             .Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1", "group1")
                               //.StartAt(runTime)
                               .WithCronSchedule("0/5 * * * * ?")
                               .Build();

            ////增加定时器
            await sched.ScheduleJob(job, trigger);

            //开启定时器
            await sched.Start();
        }
Beispiel #24
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();
        }
Beispiel #25
0
        public static void Start()
        {
            DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);
            //Schedule
            HolidayCalendar cal       = new HolidayCalendar();
            IScheduler      scheduler = StdSchedulerFactory.GetDefaultScheduler();

            scheduler.Start();

            //====================Voluntee Cleaner============================

            //Assign employees on the roster
            IJobDetail firstJob = JobBuilder.Create <FirstJob>()
                                  .WithIdentity("firstJob")
                                  .Build();
            //First Trigger
            ITrigger firstTrigger = TriggerBuilder.Create()
                                    .WithIdentity("firstTrigger")
                                    .StartAt(runTime)
                                    .WithCronSchedule("0/6 * * * * ?")
                                    .Build();

            //Change the employees status and queue number
            IJobDetail secondJob = JobBuilder.Create <SecondJob>()
                                   .WithIdentity("secondJob")
                                   .Build();
            //Second Trigger
            ITrigger secondTrigger = TriggerBuilder.Create()
                                     .WithIdentity("secondTrigger")
                                     .StartAt(runTime)
                                     .WithCronSchedule("0/5 * * * * ?")
                                     .Build();

            //====================Permanent Cleaner============================

            //Assign employees on the roster
            IJobDetail pcleanerJob = JobBuilder.Create <PCleanerJobFirst>()
                                     .WithIdentity("pcleanerJob")
                                     .Build();
            //Trigger job
            ITrigger pcleanerTrigger = TriggerBuilder.Create()
                                       .WithIdentity("pcleanerTrigger")
                                       .StartAt(runTime)
                                       .WithCronSchedule("0/6 * * * * ?")
                                       .Build();

            //Assign employees on the roster

            /*IJobDetail pcleanerJobSecond = JobBuilder.Create<PCleanerJobFirst>()
             *                              .WithIdentity("pcleanerJobSecond")
             *                              .Build();
             * //Trigger job
             * ITrigger pcleanerTriggerSecond = TriggerBuilder.Create()
             *                               .WithIdentity("pcleanerTriggerSecond")
             *                               .StartAt(runTime)
             *                               .WithCronSchedule("0 0 12 1 * ?")
             *                               .Build();*/

            //========================PERMANANT EMPLOYEES===============================

            //Cleaner Job
            IJobDetail CleanerJob = JobBuilder.Create <PClearJob>()
                                    .WithIdentity("CleanerJob")
                                    .Build();

            //Cleaner Trigger
            ITrigger CleanerTrigger = TriggerBuilder.Create()
                                      .WithIdentity("CleanerTrigger")
                                      .StartAt(runTime)
                                      .WithCronSchedule("0 1 * * * ?")
                                      .Build();

            //========================/PERMANANT EMPLOYEES===============================


            //Executing cleaners jobs
            scheduler.ScheduleJob(firstJob, firstTrigger);
            scheduler.ScheduleJob(secondJob, secondTrigger);

            //scheduler.ScheduleJob(pcleanerJob, pcleanerTrigger);
            //scheduler.ScheduleJob(CleanerJob, CleanerTrigger);
            //scheduler.ScheduleJob(pcleanerJobSecond, pcleanerTriggerSecond);

            //Executing Security dayshift jobs
            //scheduler.ScheduleJob(securityAssignJob, securityAssignTrigger);
            //scheduler.ScheduleJob(securityAssignJob2, securityAssignTrigger2);
        }
        public virtual async Task Run()
        {
            ILoggerFactory logFactory = new LoggerFactory().AddConsole();
            ILogger        logger     = logFactory.CreateLogger <SimpleExample>();

            logger.LogInformation("------- Initializing ----------------------");

            // First we must get a reference to a scheduler
            ISchedulerFactory sf    = new StdSchedulerFactory();
            IScheduler        sched = await sf.GetScheduler();

            logger.LogInformation("------- Initialization Complete -----------");

            logger.LogInformation("------- Scheduling Job  -------------------");

            // define the job and tie it to our HelloJob class
            IJobDetail job = JobBuilder.Create <HelloJob>()
                             .WithIdentity("job1", "group1")
                             .Build();

            //////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////
            // computer a time that is on the next round minute
            DateTimeOffset nextMinute       = DateBuilder.EvenMinuteDate(DateTimeOffset.UtcNow);
            DateTimeOffset fiveSecondsLater = DateBuilder.NextGivenSecondDate(null, 10);

            // 1/3
            // Bir sonraki (çift sayı) dakika
            //ITrigger trigger = TriggerBuilder.Create()
            //    .WithIdentity("trigger1", "group1")
            //    .StartAt(nextMinute)
            //    .Build();

            // 2/3
            // 3 saniyede bir, 5 kez
            ITrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                               .WithIdentity("trigger2", "group1")
                               .StartAt(fiveSecondsLater)
                               .WithSimpleSchedule(x => x.WithIntervalInSeconds(3).WithRepeatCount(5))
                               .Build();

            ////// 3 / 3
            ////// 20 ile 59. saniyeler arasında her saniye
            //ITrigger trigger = TriggerBuilder.Create()
            //    .WithIdentity("trigger3", "group1")
            //    .WithCronSchedule("20-59 * * * * ?") //0/2
            //    .Build();

            //////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////

            // Tell quartz to schedule the job using our trigger
            await sched.ScheduleJob(job, trigger);

            // Start up the scheduler (nothing can actually run until the
            // scheduler has been started)
            await sched.Start();

            logger.LogInformation("------- Started Scheduler -----------------");

            // wait long enough so that the scheduler as an opportunity to
            // run the job!
            logger.LogInformation("------- Waiting 65 seconds... -------------");

            // wait 65 seconds to show jobs
            await Task.Delay(TimeSpan.FromSeconds(65));

            // shut down the scheduler
            logger.LogInformation("------- Shutting Down ---------------------");
            await sched.Shutdown(true);

            logger.LogInformation("------- Shutdown Complete -----------------");
        }
Beispiel #27
0
        public async Task Run()
        {
            Console.WriteLine($"{DateTime.Now} Run");

            IScheduler sched = await sf.GetScheduler();

            string          fileJson = Path.Combine(dirJson, "jobs.json");
            List <JobModel> list     = new List <JobModel>();

            try
            {
                using (var stream = File.Open(fileJson, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    list = await JsonSerializer.DeserializeAsync <List <JobModel> >(stream);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            if (list == null || list.Count == 0)
            {
                return;
            }

            foreach (var item in list)
            {
                JobKey jobKey = new JobKey($"job{item.Name}", $"group{item.Name}");
                if (item.IsEnabled)
                {
                    if (await sched.CheckExists(jobKey))
                    {
                        continue;
                    }

                    if (item.IntervalSchedule == null)
                    {
                        continue;
                    }
                    if (item.IntervalSchedule.Months == 0 && item.IntervalSchedule.Days == 0 &&
                        item.IntervalSchedule.Hours == 0 && item.IntervalSchedule.Minutes == 0)
                    {
                        continue;
                    }

                    // computer a time that is on the next round minute
                    DateTimeOffset runTime = DateBuilder.EvenMinuteDate(DateTimeOffset.Now);
                    if (item.StartAt != null)
                    {
                        runTime = item.StartAt.GetDateTimeOffset();
                    }

                    Console.WriteLine($"{runTime.DateTime} DateTimeOffset {item.Name}");

                    // define the job and tie it to our SimpleJob class
                    IJobDetail job = JobBuilder.Create <SimpleJob>()
                                     .WithIdentity($"job{item.Name}", $"group{item.Name}")
                                     .UsingJobData("name", item.Name)
                                     .Build();

                    // Trigger the job to run on the next round minute
                    ITrigger trigger = TriggerBuilder.Create()
                                       .WithIdentity($"trigger{item.Name}", $"group{item.Name}")
                                       .StartAt(runTime)
                                       .WithCalendarIntervalSchedule(x =>
                    {
                        if (item.IntervalSchedule.Months > 0)
                        {
                            x.WithIntervalInMonths(item.IntervalSchedule.Months);
                        }
                        else if (item.IntervalSchedule.Days > 0)
                        {
                            x.WithIntervalInDays(item.IntervalSchedule.Days);
                        }
                        else if (item.IntervalSchedule.Hours > 0)
                        {
                            x.WithIntervalInHours(item.IntervalSchedule.Hours);
                        }
                        else if (item.IntervalSchedule.Minutes > 0)
                        {
                            x.WithIntervalInMinutes(item.IntervalSchedule.Minutes);
                        }
                    })
                                       .Build();

                    // Tell quartz to schedule the job using our trigger
                    if (!await sched.CheckExists(job.Key))
                    {
                        await sched.ScheduleJob(job, trigger);

                        listJob.Add(item);
                        Console.WriteLine($"{DateTime.Now} Add {item.Name}");
                    }
                }
                else
                {
                    // DeleteJob
                    if (await sched.CheckExists(jobKey))
                    {
                        await sched.DeleteJob(jobKey);

                        listJob.RemoveAll(x => x.Name == item.Name);
                        Console.WriteLine($"{DateTime.Now} Remove {item.Name}");
                    }
                }
            }

            // DeleteJob
            foreach (var item in listJob.Select(x => x.Name).Except(list.Select(x => x.Name)).ToList())
            {
                JobKey jobKey = new JobKey($"job{item}", $"group{item}");
                if (await sched.CheckExists(jobKey))
                {
                    await sched.DeleteJob(jobKey);

                    listJob.RemoveAll(x => x.Name == item);
                    Console.WriteLine($"{DateTime.Now} Remove {item}");
                }
            }

            // Start up the scheduler (nothing can actually run until the scheduler has been started)
            await sched.Start();
        }