Esempio n. 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews(options =>
            {
                options.Filters.Add <GatewayResultFilterAttribute>();       // 通用执行结果包装处理过滤器
                options.Filters.Add <GlobalExceptionFilterAttribute>();     // 全局异常过滤器
            })
            .AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.Converters.Add(new DateTimeConverter()); // 日期格式化
            })
            .AddFluentValidation(config =>                                             // 请求模型参数验证
            {
                config.RunDefaultMvcValidationAfterFluentValidationExecutes = true;    // false : 禁止默认模型验证
                config.ValidatorOptions.CascadeMode = CascadeMode.Stop;                // 不级联验证,第一个规则错误就停止
                config.RegisterValidatorsFromAssemblyContaining <JobCreateOrUpdateValidator>();
            });
            services.AddHostedService <NLogHostService>();                // NLog 关闭服务
            services.AddDistributedMemoryCache();                         // 分布式缓存接口, 这里使用本机内存缓存
            services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All)); // 解决中文乱码
            services.AddHttpClient();                                     // IHttpClientFactory

            /***********Quartz.NET*********/
            IConfigurationSection quartzConfiguration = Configuration.GetSection("Quartz"); // Quartz配置节点

            services.AddTransient <HttpJob>();                                              // 注册job至容器,必须步骤
            services.AddQuartz(config =>
            {
                config.UseTimeZoneConverter();
                // 使用MicrosoftDependencyInjectionJobFactory工厂类从 容器 中创建job实例
                config.UseMicrosoftDependencyInjectionJobFactory(options =>
                {
                    options.AllowDefaultConstructor = false;    // 禁止使用无参构建函数创建 job
                    options.CreateScope             = false;
                });
                config.UseDefaultThreadPool(options =>
                {
                    options.MaxConcurrency = 10;    // 最大并发执行线程数
                });
                config.UsePersistentStore(options =>
                {
                    options.UseProperties = false;
                    //options.UseBinarySerializer();  // 二进制序列化
                    options.UseJsonSerializer();    // json序列化
                    options.UseMySql(ado =>
                    {
                        ado.ConnectionString     = quartzConfiguration["Database"];
                        ado.TablePrefix          = quartzConfiguration["TablePrefix"]; // 默认值 QRTZ_
                        ado.ConnectionStringName = "Quartz.net";
                    });
                });

                // 监听器
                config.AddSchedulerListener <DefaultSchedulerListener>();
                config.AddJobListener <DefaultJobListener>();
                config.AddTriggerListener <DefaultTriggerListener>();

                // 启动NLog日志文件清除job
                config.ScheduleJob <ClearNLogJob>(trigger =>
                {
                    trigger.WithIdentity(NLogJobKey.NameKey, NLogJobKey.GroupKey).StartNow()
                    .WithCronSchedule("0 0 0 1/3 * ? ", cron => cron.WithMisfireHandlingInstructionFireAndProceed());    // 从每月1日开始,每3天执行一次
                }, job =>
                {
                    job.WithIdentity(NLogJobKey.NameKey, NLogJobKey.GroupKey)
                    .StoreDurably(false) // 是否持久化, 无关联触发器时是否移除,false:移除
                    .RequestRecovery()   // 重启后是否恢复任务
                    .WithDescription("每3天清空NLog日志文件");
                });
            });
            // IHostedService宿主启动 Quartz服务 services.AddSingleton<IHostedService, QuartzHostedService>()
            services.AddQuartzServer(options =>
            {
                // when shutting down we want jobs to complete gracefully
                options.WaitForJobsToComplete = true;   // 等待任务执行完,再退出
            });

            /***********FluentEmail*********/
            // 为了将邮件通知配置在job data上, 不使用自带的service注册方式
            //services.AddFluentEmail(quartzConfiguration["Smtp:UserName"], "Quartz.NET任务调度通知")
            //    .AddRazorRenderer()
            //    .AddSmtpSender(quartzConfiguration["Smtp:Host"], Convert.ToInt32(quartzConfiguration["Smtp:Port"]), quartzConfiguration["Smtp:UserName"], quartzConfiguration["Smtp:Password"]);
            services.AddTransient <IFluentEmail>(serviceProvider =>
            {
                IScheduler scheduler = serviceProvider.GetRequiredService <ISchedulerFactory>().GetScheduler().Result;

                JobKey key = new JobKey(EmailJobKeys.NameKey, EmailJobKeys.GroupKey);
                if (!scheduler.CheckExists(key).Result)
                {
                    JobDataMap dataMap = new JobDataMap();
                    dataMap.Put(EmailJobKeys.Host, "smtp.qq.com");
                    dataMap.Put(EmailJobKeys.Port, 587);                    // 465端口一直尝试不通过,奇怪
                    dataMap.Put(EmailJobKeys.UserName, "*****@*****.**"); // 作者qq,欢迎骚扰
                    dataMap.Put(EmailJobKeys.Password, "cirxjtemuzxycagf");
                    dataMap.Put(EmailJobKeys.To, string.Empty);             // 接收者邮件支持多个,以 ; 隔开
                    dataMap.Put(EmailJobKeys.NickName, "Quartz.NET任务调度通知");
                    dataMap.Put(EmailJobKeys.CacheExpiry, 30);              // 默认30分钟内只通知一次
                    IJobDetail job = JobBuilder.Create <HttpJob>()
                                     .StoreDurably(true)
                                     .RequestRecovery()
                                     .WithDescription("邮件通知配置Job,切勿删除")
                                     .WithIdentity(key)
                                     .UsingJobData(dataMap)
                                     .Build();
                    scheduler.AddJob(job, true);   // 初始化邮件通知配置
                }

                IJobDetail emailJob      = scheduler.GetJobDetail(key).Result;
                IFluentEmail fluentEmail = new Email(new ReplaceRenderer(),
                                                     new SmtpSender(new SmtpClient(emailJob.JobDataMap.GetString(EmailJobKeys.Host), emailJob.JobDataMap.GetInt(EmailJobKeys.Port))
                {
                    EnableSsl   = true,
                    Credentials = new NetworkCredential(emailJob.JobDataMap.GetString(EmailJobKeys.UserName),
                                                        emailJob.JobDataMap.GetString(EmailJobKeys.Password))
                }),
                                                     emailJob.JobDataMap.GetString(EmailJobKeys.UserName),
                                                     emailJob.JobDataMap.GetString(EmailJobKeys.NickName));
                return(fluentEmail);
            });

            IocEngine.Instance.Init(services);  // 实在没办法才弄个静态容器获取service, 监听器里无法通过构造函数 注入 ISchedulerFactory, IFluentEmail, 猜测应该是循环引用了
        }
Esempio n. 2
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
            .ContractResolver = new NHibernateContractResolver();

            #region Custom generic error handler
            GlobalConfiguration.Configuration.Filters.Add(
                new UnhandledExceptionFilter()
                .Register <QuestionarException>((exception, request) =>
            {
                HttpError err = new HttpError(exception, _incluirDetalhesDeErro);
                err.Message   = exception.Message;
                return(request.CreateResponse(HttpStatusCode.InternalServerError, err));
            })
                .Register <UnauthorizedAccessException>((exception, request) =>
            {
                HttpError err = new HttpError(exception, _incluirDetalhesDeErro);
                err.Message   = "Sua sessão expirou.";
                return(request.CreateResponse(HttpStatusCode.BadRequest, err));
            })
                .Register <AuthenticationException>((exception, request) =>
            {
                HttpError err = new HttpError(exception, _incluirDetalhesDeErro);
                err.Message   = LOGIN_INVALIDO;
                return(request.CreateResponse(HttpStatusCode.BadRequest, err));
            })
                .Register <ADOException>((exception, request) =>
            {
                HttpError err = new HttpError(exception, _incluirDetalhesDeErro);
                err.Message   = INCONFORMIDADE_BANCO_DADOS;
                return(request.CreateResponse(HttpStatusCode.BadRequest, err));
            })
                .Register <WebException>((exception, request) =>
            {
                HttpError err = new HttpError(exception, _incluirDetalhesDeErro);
                err.Message   = INCONFORMIDADE_NAO_ESPECIFICADA;
                return(request.CreateResponse(HttpStatusCode.BadRequest, err));
            })
                .Register <ArgumentNullException>((exception, request) =>
            {
                HttpError err = new HttpError(exception, _incluirDetalhesDeErro);
                err.Message   = INCONFORMIDADE_NAO_ESPECIFICADA;
                return(request.CreateResponse(HttpStatusCode.BadRequest, err));
            })
                .Register <EndOfStreamException>((exception, request) =>
            {
                HttpError err = new HttpError(exception, _incluirDetalhesDeErro);
                err.Message   = "Inconformidade ao ler arquivo. Por favor, tente gerar o arquivo novamente e caso o erro persista, contate o administrador do sistema.";
                return(request.CreateResponse(HttpStatusCode.BadRequest, err));
            })
                .Register <PropertyAccessException>((exception, request) =>
            {
                HttpError err = new HttpError(exception, _incluirDetalhesDeErro);
                err.Message   = INCONFORMIDADE_NAO_ESPECIFICADA;
                return(request.CreateResponse(HttpStatusCode.BadRequest, err));
            })
                .Register <NullReferenceException>((exception, request) =>
            {
                HttpError err = new HttpError(exception, _incluirDetalhesDeErro);
                err.Message   = INCONFORMIDADE_NAO_ESPECIFICADA;
                return(request.CreateResponse(HttpStatusCode.BadRequest, err));
            })
                .Register <Exception>((exception, request) =>
            {
                HttpError err = new HttpError(exception, _incluirDetalhesDeErro);
                err.Message   = INCONFORMIDADE_NAO_ESPECIFICADA;
                return(request.CreateResponse(HttpStatusCode.PreconditionFailed, err));
            })
                );
            #endregion

            #region Jobs
            // construct a scheduler factory
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

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

            IJobDetail job = JobBuilder.Create <SendQuestion>()
                             .WithIdentity("sendQuestion")
                             .Build();

            // Trigger the job to run now, and then every 40 seconds
            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("sendQuestionTrigger")
                               .StartNow()
                               .WithSimpleSchedule(x => x
                                                   .WithIntervalInHours(24)
                                                   //.WithIntervalInSeconds(60)para testes
                                                   .RepeatForever())
                               .Build();

            sched.ScheduleJob(job, trigger);
            #endregion
        }
        static async Task <IJobDetail> CreateJobDetail(ConsumeContext context, Uri destination, JobKey jobKey, Guid?tokenId = default(Guid?))
        {
            string body;

            using (var ms = new MemoryStream())
            {
                using (Stream bodyStream = context.ReceiveContext.GetBody())
                {
                    await bodyStream.CopyToAsync(ms).ConfigureAwait(false);
                }

                body = Encoding.UTF8.GetString(ms.ToArray());
            }

            if (string.Compare(context.ReceiveContext.ContentType.MediaType, JsonMessageSerializer.JsonContentType.MediaType,
                               StringComparison.OrdinalIgnoreCase)
                == 0)
            {
                body = TranslateJsonBody(body, destination.ToString());
            }
            else if (string.Compare(context.ReceiveContext.ContentType.MediaType, XmlMessageSerializer.XmlContentType.MediaType,
                                    StringComparison.OrdinalIgnoreCase) == 0)
            {
                body = TranslateXmlBody(body, destination.ToString());
            }
            else
            {
                throw new InvalidOperationException("Only JSON and XML messages can be scheduled");
            }

            JobBuilder builder = JobBuilder.Create <ScheduledMessageJob>()
                                 .RequestRecovery(true)
                                 .WithIdentity(jobKey)
                                 .UsingJobData("Destination", ToString(destination))
                                 .UsingJobData("ResponseAddress", ToString(context.ResponseAddress))
                                 .UsingJobData("FaultAddress", ToString(context.FaultAddress))
                                 .UsingJobData("Body", body)
                                 .UsingJobData("ContentType", context.ReceiveContext.ContentType.MediaType);

            if (context.MessageId.HasValue)
            {
                builder = builder.UsingJobData("MessageId", context.MessageId.Value.ToString());
            }
            if (context.CorrelationId.HasValue)
            {
                builder = builder.UsingJobData("CorrelationId", context.CorrelationId.Value.ToString());
            }
            if (context.ConversationId.HasValue)
            {
                builder = builder.UsingJobData("ConversationId", context.ConversationId.Value.ToString());
            }
            if (context.InitiatorId.HasValue)
            {
                builder = builder.UsingJobData("InitiatorId", context.InitiatorId.Value.ToString());
            }
            if (context.RequestId.HasValue)
            {
                builder = builder.UsingJobData("RequestId", context.RequestId.Value.ToString());
            }
            if (context.ExpirationTime.HasValue)
            {
                builder = builder.UsingJobData("ExpirationTime", context.ExpirationTime.Value.ToString());
            }

            if (tokenId.HasValue)
            {
                builder = builder.UsingJobData("TokenId", tokenId.Value.ToString("N"));
            }

            IJobDetail jobDetail = builder
                                   .UsingJobData("HeadersAsJson", JsonConvert.SerializeObject(context.Headers.GetAll()))
                                   .Build();

            return(jobDetail);
        }
 public IJobDetail Compose()
 {
     return(JobBuilder.Create <S>()
            .WithIdentity(this.id.ToString())
            .Build());
 }
Esempio n. 5
0
 public void ConfigureJob(JobBuilder job)
 {
     job.WithIdentity("苏州菜价行情", "菜价行情")
     .WithDescription("苏州价格在线");
 }
Esempio n. 6
0
File: Task.cs Progetto: radtek/crm
        /// <summary>
        /// 控制中心
        /// </summary>
        protected void ControlCenter()
        {
            Loggers.Debug(new DebugLogInfo()
            {
                Message = "ControlCenter"
            });

            try
            {
                //从工厂中获取一个调度器实例化
                IScheduler scheduler = StdSchedulerFactory.GetDefaultScheduler();
                scheduler.Start();       //开启调度器

                //================第三方支付通知失败处理==============================

                IJobDetail setNotificationFailedJob = JobBuilder.Create <SetNotificationFailed>()
                                                      .WithIdentity("setNotificationFailedJob", "group1")
                                                      .UsingJobData("jobSays", "Hello World!")
                                                      .Build();

                ITrigger setNotificationFailedTrigger = TriggerBuilder.Create()
                                                        .WithIdentity("setNotificationFailedTrigger", "group1")
                                                        .StartNow()
                                                        .WithCronSchedule("0 */30 * * * ?")    //时间表达式,30分钟一次
                                                        .Build();
                scheduler.ScheduleJob(setNotificationFailedJob, setNotificationFailedTrigger); //把作业、触发器加入调度器

                //===============支付中心通知失败重新通知到业务平台=================
                IJobDetail payCenterNotifyJob = JobBuilder.Create <PayCenterNotify>()
                                                .WithIdentity("payCenterNotifyJob", "group1")
                                                .UsingJobData("jobSays", "Hello World!")
                                                .Build();


                ITrigger payCenterNotifyJobTrigger = TriggerBuilder.Create()
                                                     .WithIdentity("payCenterNotifyJobTrigger", "group1")
                                                     .StartNow()
                                                     .WithCronSchedule("/5 * * ? * *") //时间表达式,5秒一次
                                                     .Build();

                scheduler.ScheduleJob(payCenterNotifyJob, payCenterNotifyJobTrigger);

                // -----------------------------------------------------------------------------------------------------
                //===============营销活动送券=================
                //IJobDetail SendCouponJob = JobBuilder.Create<MarketingActivitySendCoupon>()
                //					   .WithIdentity("SendCouponJob", "group1")
                //					   .UsingJobData("jobSays", "Hello World!")
                //					   .Build();


                //ITrigger SendCouponJobTrigger = TriggerBuilder.Create()
                //							.WithIdentity("SendCouponJobTrigger", "group1")
                //							.StartNow()
                //							.WithCronSchedule("0 */3 * * * ?")    //3分钟
                //							.Build();

                //scheduler.ScheduleJob(SendCouponJob, SendCouponJobTrigger);

                ////===============营销活动发消息=================
                //IJobDetail SendMessageJob = JobBuilder.Create<MarketingActivitySendMessage>()
                //					   .WithIdentity("SendMessageJob", "group1")
                //					   .UsingJobData("jobSays", "Hello World!")
                //					   .Build();


                //ITrigger SendMessageJobTrigger = TriggerBuilder.Create()
                //							.WithIdentity("SendMessageJobTrigger", "group1")
                //							.StartNow()
                //							.WithCronSchedule("0 */3 * * * ?")    //3分钟
                //							.Build();

                //scheduler.ScheduleJob(SendMessageJob, SendMessageJobTrigger);

                ////=================角色菜单缓存种植====================
                IJobDetail setRoleMenuJob = JobBuilder.Create <SetRedisRoleCache>()
                                            .WithIdentity("setRoleMenuJob", "group1")
                                            .UsingJobData("jobSays", "Hello World!")
                                            .Build();

                ITrigger setRoleMenuJobTrigger = TriggerBuilder.Create()
                                                 .WithIdentity("setRoleMenuJobTrigger", "group1")
                                                 .StartNow()
                                                 .WithCronSchedule("0 0 1 * * ?")                                             //  每天 1点 触发
                                                 .Build();

                scheduler.ScheduleJob(setRoleMenuJob, setRoleMenuJobTrigger);

                ////=================订单支付完成 队列 消息处理====================
                IJobDetail processPaySuccessJob = JobBuilder.Create <ProcessOrderPaySuccess>()
                                                  .WithIdentity("processPaySuccessJob", "group1")
                                                  .UsingJobData("jobSays", "Hello World!")
                                                  .Build();

                ITrigger processPaySuccessJobTrigger = TriggerBuilder.Create()
                                                       .WithIdentity("processPaySuccessJobTrigger", "group1")
                                                       .StartNow()
                                                       .WithCronSchedule("/10 * * ? * *")                                                //  10s 一次
                                                       .Build();

                scheduler.ScheduleJob(processPaySuccessJob, processPaySuccessJobTrigger);

                ////=================订单服务完成后,15天用户未确认,自动确认处理====================
                IJobDetail processOrderConfrim = JobBuilder.Create <ProcessOrderConfrim>()
                                                 .WithIdentity("processOrderConfrim", "group1")
                                                 .UsingJobData("jobSays", "Hello World!")
                                                 .Build();

                ITrigger processOrderConfrimTrigger = TriggerBuilder.Create()
                                                      .WithIdentity("processOrderConfrimTrigger", "group1")
                                                      .StartNow()
                                                      //.WithCronSchedule("0 0 1 * * ?")   //  10s 一次
                                                      .WithCronSchedule("0 */3 * * * ?")
                                                      .Build();
                //一天一次 0 0 1 * * ?
                scheduler.ScheduleJob(processOrderConfrim, processOrderConfrimTrigger);


                ////=================APP/后台订单发货-发送微信模板消息 队伍 消息处理====================
                IJobDetail processOrderSendJob = JobBuilder.Create <ProcessOrderSend>()
                                                 .WithIdentity("processOrderSendJob", "group1")
                                                 .UsingJobData("jobSays", "Hello World!")
                                                 .Build();

                ITrigger processOrderSendJobTrigger = TriggerBuilder.Create()
                                                      .WithIdentity("processOrderSendJobTrigger", "group1")
                                                      .StartNow()
                                                      .WithCronSchedule("/10 * * ? * *")                                                 //  10s 一次
                                                      .Build();

                scheduler.ScheduleJob(processOrderSendJob, processOrderSendJobTrigger);//这里是新建的job**

                ////=================确认收货时处理积分、返现、佣金 队伍 队伍 消息处理====================
                IJobDetail processOrderRewardJob = JobBuilder.Create <ProcessOrderReward>()
                                                   .WithIdentity("processOrderRewardJob", "group1")
                                                   .UsingJobData("jobSays", "Hello World!")
                                                   .Build();

                ITrigger processOrderRewardJobTrigger = TriggerBuilder.Create()
                                                        .WithIdentity("processOrderRewardJobTrigger", "group1")
                                                        .StartNow()
                                                        .WithCronSchedule("/10 * * ? * *")                                               //  10s 一次
                                                        .Build();

                scheduler.ScheduleJob(processOrderRewardJob, processOrderRewardJobTrigger);


                ////=================商户数据库链接缓存种植====================
                IJobDetail setConnectionJob = JobBuilder.Create <SetRedisConnectionCache>()
                                              .WithIdentity("setConnectionJob", "group1")
                                              .UsingJobData("jobSays", "Hello World!")
                                              .Build();

                ITrigger setConnectionJobTrigger = TriggerBuilder.Create()
                                                   .WithIdentity("setConnectionJobTrigger", "group1")
                                                   .StartNow()
                                                   .WithCronSchedule("0 0 1 * * ?")                                           //  每天 1点 触发
                                                   .Build();

                scheduler.ScheduleJob(setConnectionJob, setConnectionJobTrigger);
                //=================奖品池队列种植====================
                IJobDetail setPrizePoolsJob = JobBuilder.Create <SetPrizePools>()
                                              .WithIdentity("setPrizePoolsJob", "group1")
                                              .UsingJobData("jobSays", "Hello World!")
                                              .Build();

                ITrigger setPrizePoolsJobTrigger = TriggerBuilder.Create()
                                                   .WithIdentity("setPrizePoolsJobTrigger", "group1")
                                                   .StartNow()
                                                   .WithCronSchedule("0 0 1 * * ?")                                           //  每天 1点 触发
                                                   .Build();

                scheduler.ScheduleJob(setPrizePoolsJob, setPrizePoolsJobTrigger);
                //=================优惠券队列种植====================
                IJobDetail setCouponJob = JobBuilder.Create <SetCoupon>()
                                          .WithIdentity("setCouponJob", "group1")
                                          .UsingJobData("jobSays", "Hello World!")
                                          .Build();

                ITrigger setCouponJobTrigger = TriggerBuilder.Create()
                                               .WithIdentity("setCouponJobTrigger", "group1")
                                               .StartNow()
                                               .WithCronSchedule("0 0 1 * * ?")                                               //  每天 1点 触发
                                               .Build();

                scheduler.ScheduleJob(setCouponJob, setCouponJobTrigger);
                //=================触点 队列 消息处理====================
                IJobDetail contactJob = JobBuilder.Create <SetContact>()
                                        .WithIdentity("contactJob", "group1")
                                        .UsingJobData("jobSays", "Hello World!")
                                        .Build();

                ITrigger contactJobTrigger = TriggerBuilder.Create()
                                             .WithIdentity("contactJobTrigger", "group1")
                                             .StartNow()
                                             .WithCronSchedule("/40 * * ? * *")                                                          //  10s 一次
                                             .Build();

                scheduler.ScheduleJob(contactJob, contactJobTrigger);
                //=================vip绑定优惠券 队列 消息处理====================
                IJobDetail vipMappingCouponJob = JobBuilder.Create <VipMappingCoupon>()
                                                 .WithIdentity("vipMappingCouponJob", "group1")
                                                 .UsingJobData("jobSays", "Hello World!")
                                                 .Build();

                ITrigger vipMappingCouponJobTrigger = TriggerBuilder.Create()
                                                      .WithIdentity("vipMappingCouponJobTrigger", "group1")
                                                      .StartNow()
                                                      .WithCronSchedule("/20 * * ? * *")                                                 //  40s 一次
                                                      .Build();

                scheduler.ScheduleJob(vipMappingCouponJob, vipMappingCouponJobTrigger);
                //=================虚拟商品发优惠券成功后通知====================
                IJobDetail _CouponCouponNoticeGetJob = JobBuilder.Create <CouponCouponNoticeGetJob>()
                                                       .WithIdentity("CouponCouponNoticeGetJob", "group1")
                                                       .UsingJobData("jobSays", "Hello World!")
                                                       .Build();

                ITrigger _CouponCouponNoticeGetJobTrigger = TriggerBuilder.Create()
                                                            .WithIdentity("CouponCouponNoticeGetJobTrigger", "group1")
                                                            .StartNow()
                                                            .WithCronSchedule("/20 * * ? * *")                                           //  40s 一次
                                                            .Build();

                scheduler.ScheduleJob(_CouponCouponNoticeGetJob, _CouponCouponNoticeGetJobTrigger);//绑定job和trigger


                ////=================商户基础设置缓存种植====================
                IJobDetail setBasicSettingJob = JobBuilder.Create <SetBasicSettingCache>()
                                                .WithIdentity("setBasicSettingJob", "group1")
                                                .UsingJobData("jobSays", "Hello World!")
                                                .Build();

                ITrigger setBasicSettingJobTrigger = TriggerBuilder.Create()
                                                     .WithIdentity("setBasicSettingJobTrigger", "group1")
                                                     .StartNow()
                                                     .WithCronSchedule("0 0 1 * * ?") //  每天 1点 触发
                                                                                      //      .WithCronSchedule("0 */3 * * * ?")    //3分钟     (为了方便测试,临时设为三分钟一次)
                                                     .Build();

                scheduler.ScheduleJob(setBasicSettingJob, setBasicSettingJobTrigger);


                ////=================订单未付款模板消息种植====================
                IJobDetail processOrderNotPaySetJob = JobBuilder.Create <ProcessOrderNotPaySet>()
                                                      .WithIdentity("ProcessOrderNotPaySetJob", "group1")
                                                      .UsingJobData("jobSays", "Hello World!")
                                                      .Build();

                ITrigger processOrderNotPaySetJobTrigger = TriggerBuilder.Create()
                                                           .WithIdentity("processOrderNotPaySetJobTrigger", "group1")
                                                           .StartNow()
                                                           .WithCronSchedule("0 0 1 * * ?") //  每天 1点 触发
                                                                                            //   .WithCronSchedule("0 */3 * * * ?")    //3分钟     (为了方便测试,临时设为三分钟一次)
                                                           .Build();

                scheduler.ScheduleJob(processOrderNotPaySetJob, processOrderNotPaySetJobTrigger);

                ////=================订单未付款模板消息发送====================
                IJobDetail processOrderNotPayGetJob = JobBuilder.Create <ProcessOrderNotPayGet>()
                                                      .WithIdentity("ProcessOrderNotPayGetJob", "group1")
                                                      .UsingJobData("jobSays", "Hello World!")
                                                      .Build();

                ITrigger processOrderNotPayGetJobTrigger = TriggerBuilder.Create()
                                                           .WithIdentity("processOrderNotPayGetJobTrigger", "group1")
                                                           .StartNow()
                                                                                              //     .WithCronSchedule("0 0 9 * * ?")  //  每天 1点 触发
                                                           .WithCronSchedule("0 */3 * * * ?") //3分钟     (为了方便测试,临时设为三分钟一次)
                                                           .Build();

                scheduler.ScheduleJob(processOrderNotPayGetJob, processOrderNotPayGetJobTrigger);


                ////=================优惠券即将过期  种植缓存====================
                IJobDetail CouponToBeExpiredMsgSetJob = JobBuilder.Create <CouponToBeExpiredMsgSetJob>()
                                                        .WithIdentity("CouponToBeExpiredMsgSetJob", "group1")
                                                        .UsingJobData("jobSays", "Hello World!")
                                                        .Build();

                ITrigger CouponToBeExpiredMsgSetJobTrigger = TriggerBuilder.Create()
                                                             .WithIdentity("CouponToBeExpiredMsgSetJobTrigger", "group1")
                                                             .StartNow()
                                                             .WithCronSchedule("0 0 1 * * ?") //  每天 1点 触发
                                                                                              //   .WithCronSchedule("0 */3 * * * ?")    //3分钟       (为了方便测试,临时设为三分钟一次)
                                                             .Build();

                scheduler.ScheduleJob(CouponToBeExpiredMsgSetJob, CouponToBeExpiredMsgSetJobTrigger);


                ////=================优惠券即将过期     发送====================
                IJobDetail CouponToBeExpiredMsgGetJob = JobBuilder.Create <CouponToBeExpiredMsgGetJob>()
                                                        .WithIdentity("CouponToBeExpiredMsgGetJob", "group1")
                                                        .UsingJobData("jobSays", "Hello World!")
                                                        .Build();

                ITrigger CouponToBeExpiredMsgGetJobTrigger = TriggerBuilder.Create()
                                                             .WithIdentity("CouponToBeExpiredMsgGetJobTrigger", "group1")
                                                             .StartNow()
                                                             .WithCronSchedule("0 0 9 * * ?") //  每天 9点 触发
                                                                                              //   .WithCronSchedule("0 */3 * * * ?")   //3分钟       (为了方便测试,临时设为三分钟一次)

                                                             .Build();

                scheduler.ScheduleJob(CouponToBeExpiredMsgGetJob, CouponToBeExpiredMsgGetJobTrigger);
                //=================计算超级分销商分润佣金====================
                IJobDetail calculateSuperRetailTraderOrderJob = JobBuilder.Create <CalculateSuperRetailTraderOrder>()
                                                                .WithIdentity("calculateSuperRetailTraderOrderJob", "group1")
                                                                .UsingJobData("jobSays", "Hello World!")
                                                                .Build();

                ITrigger calculateSuperRetailTraderOrderJobTrigger = TriggerBuilder.Create()
                                                                     .WithIdentity("calculateSuperRetailTraderOrderJobTrigger", "group1")
                                                                     .StartNow()
                                                                     .WithCronSchedule("/40 * * ? * *")                                  //  40s 一次
                                                                     .Build();
                scheduler.ScheduleJob(calculateSuperRetailTraderOrderJob, calculateSuperRetailTraderOrderJobTrigger);

                //=================根据订单状态,做出不同的推送消息(员工(客服)或者会员)====================
                IJobDetail ProcessOrderPushMessageJob = JobBuilder.Create <ProcessOrderPushMessage>()
                                                        .WithIdentity("ProcessOrderPushMessageJob", "group1")
                                                        .UsingJobData("jobSays", "Hello World!")
                                                        .Build();

                ITrigger ProcessOrderPushMessageJobTrigger = TriggerBuilder.Create()
                                                             .WithIdentity("ProcessOrderPushMessageJobTrigger", "group1")
                                                             .StartNow()
                                                             .WithCronSchedule("/30 * * ? * *")                                          //  30s 一次
                                                             .Build();
                scheduler.ScheduleJob(ProcessOrderPushMessageJob, ProcessOrderPushMessageJobTrigger);
                //=================计算售卡分润====================
                IJobDetail calculateSalesVipCardOrderJob = JobBuilder.Create <SalesVipCardOrder>()
                                                           .WithIdentity("calculateSalesVipCardOrderJob", "group1")
                                                           .UsingJobData("jobSays", "Hello World!")
                                                           .Build();

                ITrigger calculateSalesVipCardOrderJobTrigger = TriggerBuilder.Create()
                                                                .WithIdentity("calculateSalesVipCardOrderJobTrigger", "group1")
                                                                .StartNow()
                                                                .WithCronSchedule("/40 * * ? * *")                                                                                                                                           //  40s 一次
                                                                .Build();
                scheduler.ScheduleJob(calculateSalesVipCardOrderJob, calculateSalesVipCardOrderJobTrigger);
                //=================计算充值分润====================
                IJobDetail CalculateRechargeOrderJob = JobBuilder.Create <RechargeOrder>()
                                                       .WithIdentity("CalculateRechargeOrderJob", "group1")
                                                       .UsingJobData("jobSays", "Hello World!")
                                                       .Build();

                ITrigger CalculateRechargeOrderJobTrigger = TriggerBuilder.Create()
                                                            .WithIdentity("CalculateRechargeOrderJobTrigger", "group1")
                                                            .StartNow()
                                                            .WithCronSchedule("/40 * * ? * *")                                                                                                                                               //  40s 一次
                                                            .Build();
                scheduler.ScheduleJob(CalculateRechargeOrderJob, CalculateRechargeOrderJobTrigger);
                //=================消费升级====================
                IJobDetail CalculateVipConsumeForUpgradeJob = JobBuilder.Create <VipConsumeForUpgradeOrder>()
                                                              .WithIdentity("CalculateVipConsumeForUpgradeJob", "group1")
                                                              .UsingJobData("jobSays", "Hello World!")
                                                              .Build();

                ITrigger CalculateVipConsumeForUpgradeJobTrigger = TriggerBuilder.Create()
                                                                   .WithIdentity("CalculateVipConsumeForUpgradeJobTrigger", "group1")
                                                                   .StartNow()
                                                                   .WithCronSchedule("/40 * * ? * *")                                                                                                                                        //  40s 一次
                                                                   .Build();
                scheduler.ScheduleJob(CalculateVipConsumeForUpgradeJob, CalculateVipConsumeForUpgradeJobTrigger);
            }
            catch (Exception ex)
            {
                Loggers.Exception(new ExceptionLogInfo(ex));
                Loggers.Debug(new DebugLogInfo()
                {
                    Message = ex.Message
                });
            }

            //scheduler.Shutdown();         //关闭调度器。
        }
Esempio n. 7
0
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(ListenerExample));

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

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

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

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

            // schedule a job to run immediately
            IJobDetail job = JobBuilder.Create <SimpleJob1>()
                             .WithIdentity("job1")
                             .Build();

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("trigger1")
                               .StartNow()
                               .Build();

            // Set up the listener
            IJobListener      listener = new Job1Listener();
            IMatcher <JobKey> matcher  = KeyMatcher <JobKey> .KeyEquals(job.Key);

            sched.ListenerManager.AddJobListener(listener, matcher);

            // schedule the job to run
            sched.ScheduleJob(job, trigger);

            // All of the jobs have been added to the scheduler, but none of the jobs
            // will run until the scheduler has been started
            log.Info("------- Starting Scheduler ----------------");
            sched.Start();

            // wait 30 seconds:
            // note:  nothing will run
            log.Info("------- Waiting 30 seconds... --------------");
            try
            {
                // wait 30 seconds to show jobs
                Thread.Sleep(TimeSpan.FromSeconds(30));
                // executing...
            }
            catch (ThreadInterruptedException)
            {
            }


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

            SchedulerMetaData metaData = sched.GetMetaData();

            log.Info(string.Format("Executed {0} jobs.", metaData.NumberOfJobsExecuted));
        }
Esempio n. 8
0
        protected override void OnStart(string[] args)
        {
            try
            {
                // construct a scheduler factory
                ISchedulerFactory schedFact = new StdSchedulerFactory();

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

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

                // Trigger the job to run now, and then every 40 seconds
                //ITrigger trigger = TriggerBuilder.Create()
                //  .WithIdentity("myTrigger", "group1")
                //  .StartNow()
                //  .WithSimpleSchedule(x => x
                //      .WithIntervalInSeconds(40)
                //      .RepeatForever())
                //  .Build();

                ITrigger trigger;


                //holiday calendar
                //HolidayCalendar cal = new HolidayCalendar();
                //cal.AddExcludedDate(DateTime.Now.AddDays(1));

                //sched.AddCalendar("myHolidays", cal, false,false);

                if (CSMV3Function.GetIsDaily())
                {
                    logger.Debug("Start Daily");
                    trigger = TriggerBuilder.Create()
                              .WithIdentity("myTrigger")
                              .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(CSMV3Function.GetHour(),
                                                                                     CSMV3Function.GetMinutes())) // execute job daily at
                                                                                                                  //.ModifiedByCalendar("myHolidays") // but not on holidays
                              .Build();
                }
                else if (CSMV3Function.GetIsWeekly())
                {
                    logger.Debug("Start Weekly");
                    logger.Debug("Day of week is : " + CSMV3Function.GetDayofWeek());
                    trigger = TriggerBuilder.Create()
                              .WithIdentity("myTrigger")
                              .WithSchedule(CronScheduleBuilder.WeeklyOnDayAndHourAndMinute(CSMV3Function.GetDayofWeek(),
                                                                                            CSMV3Function.GetHour(),
                                                                                            CSMV3Function.GetMinutes())) // execute job daily at
                                                                                                                         //.ModifiedByCalendar("myHolidays") // but not on holidays
                              .Build();
                }
                else if (CSMV3Function.GetIsMonthly())
                {
                    logger.Debug("Start Monthly");
                    logger.Debug("Day of month is : " + CSMV3Function.GetDayofMonth());
                    trigger = TriggerBuilder.Create()
                              .WithIdentity("myTrigger")
                              .WithSchedule(CronScheduleBuilder.MonthlyOnDayAndHourAndMinute(CSMV3Function.GetDayofMonth(),
                                                                                             CSMV3Function.GetHour(),
                                                                                             CSMV3Function.GetMinutes())) // execute job daily at
                                                                                                                          //.ModifiedByCalendar("myHolidays") // but not on holidays
                              .Build();
                }
                else
                {
                    trigger = TriggerBuilder.Create()
                              .WithIdentity("myTrigger", "group1")
                              .WithSimpleSchedule(x => x
                                                  .WithIntervalInSeconds(CSMV3Function.GetIntervalinSeconds())
                                                  .RepeatForever())
                              .Build();
                }



                sched.ScheduleJob(job, trigger);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                logger.Error(ex.InnerException);
                throw;
            }
        }
Esempio n. 9
0
        private void ScheduleJobs()
        {
            // Initialize Quartz
            ISchedulerFactory schedulerFactory = new StdSchedulerFactory();

            _scheduler            = schedulerFactory.GetScheduler();
            _scheduler.JobFactory = new NinjectJobFactory(_kernel);

            TimeZoneInfo easternTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            bool         isDaylight      = easternTimeZone.IsDaylightSavingTime(DateTime.Now);

            DateTimeOffset morning = DateBuilder.NewDateInTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"))
                                     .AtHourMinuteAndSecond(7, 30, 0)
                                     .Build();

            //DateTimeOffset morning = DateBuilder.FutureDate(10, IntervalUnit.Second);

            DateTimeOffset marketAlertTimeInMorning = DateBuilder.NewDateInTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"))
                                                      .AtHourMinuteAndSecond(isDaylight ? 7 : 8, 45, 0)
                                                      .Build();

            //DateTimeOffset marketAlertTimeInMorning = DateBuilder.FutureDate(10, IntervalUnit.Second);

            DateTimeOffset suspendedPaymentTimeInMorning = DateBuilder.NewDateInTimeZone(TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"))
                                                           .AtHourMinuteAndSecond(11, 0, 0)
                                                           .Build();

            // Schedule task for trial expiries
            IJobDetail trialExpiryJobDetail       = JobBuilder.Create <TrialExpiredJob>().WithIdentity("Trial Expiry Emails").Build();
            ITrigger   dailyTriggerForTrialExpiry = TriggerBuilder.Create()
                                                    .WithIdentity("Daily Trigger (Trial Expiries)")
                                                    .StartAt(morning)
                                                    .WithSimpleSchedule(schedule => schedule.WithInterval(TimeSpan.FromDays(1)).RepeatForever())
                                                    .ForJob(trialExpiryJobDetail)
                                                    .Build();

            _scheduler.ScheduleJob(trialExpiryJobDetail, dailyTriggerForTrialExpiry);

            // Schedule task for email being sent to inactive members
            IJobDetail inactiveMembersJobDetail       = JobBuilder.Create <InactiveMembersJob>().WithIdentity("Inactive Member Emails").Build();
            ITrigger   dailyTriggerForInactiveMembers = TriggerBuilder.Create()
                                                        .WithIdentity("Daily Trigger (Inactive Members)")
                                                        .StartAt(morning)
                                                        .WithSimpleSchedule(schedule => schedule.WithInterval(TimeSpan.FromDays(1)).RepeatForever())
                                                        .ForJob(inactiveMembersJobDetail)
                                                        .Build();

            _scheduler.ScheduleJob(inactiveMembersJobDetail, dailyTriggerForInactiveMembers);

            // Schedule task for email being sent to people who have not signed up after their trial expiry
            IJobDetail userFeedbackJobDetail       = JobBuilder.Create <LostUserFeedbackRequestJob>().WithIdentity("User Feedback Emails").Build();
            ITrigger   dailyTriggerForUserFeedback = TriggerBuilder.Create()
                                                     .WithIdentity("Daily Trigger (User Feedback)")
                                                     .StartAt(morning)
                                                     .WithSimpleSchedule(schedule => schedule.WithInterval(TimeSpan.FromDays(1)).RepeatForever())
                                                     .ForJob(userFeedbackJobDetail)
                                                     .Build();

            _scheduler.ScheduleJob(userFeedbackJobDetail, dailyTriggerForUserFeedback);

            // Schedule task for morning market alert
            IJobDetail morningMarketAlertJobDetail    = JobBuilder.Create <MorningMarketAlertJob>().WithIdentity("Morning Market Alert").Build();
            ITrigger   dailyMorningMarketAlertTrigger = TriggerBuilder.Create()
                                                        .WithIdentity("Daily Trigger (Morning Market Alert)")
                                                        .StartAt(marketAlertTimeInMorning)
                                                        .WithSimpleSchedule(schedule => schedule.WithInterval(TimeSpan.FromDays(1)).RepeatForever())
                                                        .ForJob(morningMarketAlertJobDetail)
                                                        .Build();

            _scheduler.ScheduleJob(morningMarketAlertJobDetail, dailyMorningMarketAlertTrigger);

            // Schedule task for failed payments
            IJobDetail paymentSuspendedJob            = JobBuilder.Create <SuspendedPaymentJob>().WithIdentity("Payment Suspended Job").Build();
            ITrigger   weeklyPaymentSuspensionTrigger = TriggerBuilder.Create()
                                                        .WithIdentity("Weekly Trigger (Payment Suspensions)")
                                                        .StartAt(suspendedPaymentTimeInMorning)
                                                        .WithSimpleSchedule(schedule => schedule.WithInterval(TimeSpan.FromDays(7)).RepeatForever())
                                                        .ForJob(paymentSuspendedJob)
                                                        .Build();

            _scheduler.ScheduleJob(paymentSuspendedJob, weeklyPaymentSuspensionTrigger);

            // Finally, start the scheduler
            _scheduler.Start();
        }
Esempio n. 10
0
        public void ConfigureServices(IServiceCollection services)
        {
            //var environment = "";

            //var hostBuilder = new HostBuilder()
            //    .UseContentRoot(Directory.GetCurrentDirectory())
            //    .ConfigureAppConfiguration((hostingContext, config) =>
            //    {
            //        environment = hostingContext.HostingEnvironment.EnvironmentName;
            //    });

            var configBuilder = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
            //if (environment.Length > 0)
            //    configBuilder.AddJsonFile($"appsettings.{environment}.json", optional: false, reloadOnChange: true);
            //configBuilder.AddEnvironmentVariables();

            IConfiguration config = configBuilder.Build();

            this._configuration = config;

            var pollingInterval = 0;

            try
            {
                pollingInterval = this._configuration.GetSection("ScheduleSettings").GetValue <int>("pollingInterval");
            }
            catch (Exception ex)
            {
                pollingInterval = 30;
            }

            Console.Out.WriteLineAsync($"Polling interval set to {pollingInterval}");

            services.AddQuartz(q =>
            {
                // construct a scheduler factory
                StdSchedulerFactory factory = new StdSchedulerFactory();

                // get a scheduler
                IScheduler scheduler = factory.GetScheduler().GetAwaiter().GetResult();
                scheduler.Start();

                // base quartz scheduler, job and trigger configuration
                IJobDetail job = JobBuilder.Create <SampleJob>()
                                 .WithIdentity("mySampleJob", "group1")
                                 .Build();

                // Trigger the job to run now, and then every [pollingInterval] seconds
                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity("mySampleTrigger1", "group1")
                                   .StartNow()
                                   .WithSimpleSchedule(x => x
                                                       .WithIntervalInSeconds(pollingInterval)
                                                       .RepeatForever())
                                   .Build();

                scheduler.ScheduleJob(job, trigger);

                // Schedule the daily lunch break.
                IJobDetail lunchJob = JobBuilder.Create <LunchJob>()
                                      .WithIdentity("mySampleLunchJob", "group1")
                                      .Build();

                ITrigger cronTriggerLunch = TriggerBuilder.Create()
                                            .WithIdentity("mySampleTrigger2", "group1")
                                            .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(2, 00))
                                            .ForJob(lunchJob)
                                            .Build();

                scheduler.ScheduleJob(lunchJob, cronTriggerLunch);

                // Schedule monthly staff pay transfer.
                IJobDetail payTransferJob = JobBuilder.Create <TransferPayJob>()
                                            .WithIdentity("mySamplePayTransferJob", "group1")
                                            .Build();

                ITrigger cronTriggerTheyGetPaid = TriggerBuilder.Create()
                                                  .WithIdentity("mySampleTrigger3", "group1")
                                                  .WithCronSchedule("0 1 2 4 * ? ")
                                                  .ForJob(payTransferJob)
                                                  .Build();

                scheduler.ScheduleJob(payTransferJob, cronTriggerTheyGetPaid);
            });

            // ASP.NET Core hosting
            services.AddQuartzServer(options =>
            {
                // when shutting down we want jobs to complete gracefully
                options.WaitForJobsToComplete = true;
            });

            services.AddHostedService <TimedHostedService>();
        }
        protected virtual void ProcessInternal(string xml)
        {
            PrepForProcessing();

#if XML_SCHEMA
            ValidateXml(xml);
#endif // XML_SCHEMA
            MaybeThrowValidationException();

            // deserialize as object model
            XmlSerializer            xs   = new XmlSerializer(typeof(QuartzXmlConfiguration20));
            QuartzXmlConfiguration20 data = (QuartzXmlConfiguration20)xs.Deserialize(new StringReader(xml));

            if (data == null)
            {
                throw new SchedulerConfigException("Job definition data from XML was null after deserialization");
            }

            //
            // Extract pre-processing commands
            //
            if (data.preprocessingcommands != null)
            {
                foreach (preprocessingcommandsType command in data.preprocessingcommands)
                {
                    if (command.deletejobsingroup != null)
                    {
                        foreach (string s in command.deletejobsingroup)
                        {
                            string deleteJobGroup = s.NullSafeTrim();
                            if (!string.IsNullOrEmpty(deleteJobGroup))
                            {
                                jobGroupsToDelete.Add(deleteJobGroup);
                            }
                        }
                    }
                    if (command.deletetriggersingroup != null)
                    {
                        foreach (string s in command.deletetriggersingroup)
                        {
                            string deleteTriggerGroup = s.NullSafeTrim();
                            if (!string.IsNullOrEmpty(deleteTriggerGroup))
                            {
                                triggerGroupsToDelete.Add(deleteTriggerGroup);
                            }
                        }
                    }
                    if (command.deletejob != null)
                    {
                        foreach (preprocessingcommandsTypeDeletejob s in command.deletejob)
                        {
                            string name  = s.name.TrimEmptyToNull();
                            string group = s.group.TrimEmptyToNull();

                            if (name == null)
                            {
                                throw new SchedulerConfigException("Encountered a 'delete-job' command without a name specified.");
                            }
                            jobsToDelete.Add(new JobKey(name, group));
                        }
                    }
                    if (command.deletetrigger != null)
                    {
                        foreach (preprocessingcommandsTypeDeletetrigger s in command.deletetrigger)
                        {
                            string name  = s.name.TrimEmptyToNull();
                            string group = s.group.TrimEmptyToNull();

                            if (name == null)
                            {
                                throw new SchedulerConfigException("Encountered a 'delete-trigger' command without a name specified.");
                            }
                            triggersToDelete.Add(new TriggerKey(name, group));
                        }
                    }
                }
            }

            if (Log.IsDebugEnabled())
            {
                Log.Debug("Found " + jobGroupsToDelete.Count + " delete job group commands.");
                Log.Debug("Found " + triggerGroupsToDelete.Count + " delete trigger group commands.");
                Log.Debug("Found " + jobsToDelete.Count + " delete job commands.");
                Log.Debug("Found " + triggersToDelete.Count + " delete trigger commands.");
            }

            //
            // Extract directives
            //
            if (data.processingdirectives != null && data.processingdirectives.Length > 0)
            {
                bool overWrite = data.processingdirectives[0].overwriteexistingdata;
                Log.Debug("Directive 'overwrite-existing-data' specified as: " + overWrite);
                OverWriteExistingData = overWrite;
            }
            else
            {
                Log.Debug("Directive 'overwrite-existing-data' not specified, defaulting to " + OverWriteExistingData);
            }

            if (data.processingdirectives != null && data.processingdirectives.Length > 0)
            {
                bool ignoreduplicates = data.processingdirectives[0].ignoreduplicates;
                Log.Debug("Directive 'ignore-duplicates' specified as: " + ignoreduplicates);
                IgnoreDuplicates = ignoreduplicates;
            }
            else
            {
                Log.Debug("Directive 'ignore-duplicates' not specified, defaulting to " + IgnoreDuplicates);
            }

            if (data.processingdirectives != null && data.processingdirectives.Length > 0)
            {
                bool scheduleRelative = data.processingdirectives[0].scheduletriggerrelativetoreplacedtrigger;
                Log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' specified as: " + scheduleRelative);
                ScheduleTriggerRelativeToReplacedTrigger = scheduleRelative;
            }
            else
            {
                Log.Debug("Directive 'schedule-trigger-relative-to-replaced-trigger' not specified, defaulting to " + ScheduleTriggerRelativeToReplacedTrigger);
            }

            //
            // Extract Job definitions...
            //
            List <jobdetailType> jobNodes = new List <jobdetailType>();
            if (data.schedule != null)
            {
                foreach (var schedule in data.schedule)
                {
                    if (schedule?.job != null)
                    {
                        jobNodes.AddRange(schedule.job);
                    }
                }
            }

            Log.Debug("Found " + jobNodes.Count + " job definitions.");

            foreach (jobdetailType jobDetailType in jobNodes)
            {
                string jobName              = jobDetailType.name.TrimEmptyToNull();
                string jobGroup             = jobDetailType.group.TrimEmptyToNull();
                string jobDescription       = jobDetailType.description.TrimEmptyToNull();
                string jobTypeName          = jobDetailType.jobtype.TrimEmptyToNull();
                bool   jobDurability        = jobDetailType.durable;
                bool   jobRecoveryRequested = jobDetailType.recover;

                Type jobType = TypeLoadHelper.LoadType(jobTypeName);


                IJobDetail jobDetail = JobBuilder.Create(jobType)
                                       .WithIdentity(jobName, jobGroup)
                                       .WithDescription(jobDescription)
                                       .StoreDurably(jobDurability)
                                       .RequestRecovery(jobRecoveryRequested)
                                       .Build();

                if (jobDetailType.jobdatamap != null && jobDetailType.jobdatamap.entry != null)
                {
                    foreach (entryType entry in jobDetailType.jobdatamap.entry)
                    {
                        string key   = entry.key.TrimEmptyToNull();
                        string value = entry.value.TrimEmptyToNull();
                        jobDetail.JobDataMap.Add(key, value);
                    }
                }

                if (Log.IsDebugEnabled())
                {
                    Log.Debug("Parsed job definition: " + jobDetail);
                }

                AddJobToSchedule(jobDetail);
            }

            //
            // Extract Trigger definitions...
            //

            List <triggerType> triggerEntries = new List <triggerType>();
            if (data.schedule != null)
            {
                foreach (var schedule in data.schedule)
                {
                    if (schedule != null && schedule.trigger != null)
                    {
                        triggerEntries.AddRange(schedule.trigger);
                    }
                }
            }

            Log.Debug("Found " + triggerEntries.Count + " trigger definitions.");

            foreach (triggerType triggerNode in triggerEntries)
            {
                string triggerName        = triggerNode.Item.name.TrimEmptyToNull();
                string triggerGroup       = triggerNode.Item.group.TrimEmptyToNull();
                string triggerDescription = triggerNode.Item.description.TrimEmptyToNull();
                string triggerCalendarRef = triggerNode.Item.calendarname.TrimEmptyToNull();
                string triggerJobName     = triggerNode.Item.jobname.TrimEmptyToNull();
                string triggerJobGroup    = triggerNode.Item.jobgroup.TrimEmptyToNull();

                int triggerPriority = TriggerConstants.DefaultPriority;
                if (!triggerNode.Item.priority.IsNullOrWhiteSpace())
                {
                    triggerPriority = Convert.ToInt32(triggerNode.Item.priority);
                }

                DateTimeOffset triggerStartTime = SystemTime.UtcNow();
                if (triggerNode.Item.Item != null)
                {
                    if (triggerNode.Item.Item is DateTime)
                    {
                        triggerStartTime = new DateTimeOffset((DateTime)triggerNode.Item.Item);
                    }
                    else
                    {
                        triggerStartTime = triggerStartTime.AddSeconds(Convert.ToInt32(triggerNode.Item.Item));
                    }
                }

                DateTime?triggerEndTime = triggerNode.Item.endtimeSpecified ? triggerNode.Item.endtime : (DateTime?)null;

                IScheduleBuilder sched;

                if (triggerNode.Item is simpleTriggerType)
                {
                    simpleTriggerType simpleTrigger        = (simpleTriggerType)triggerNode.Item;
                    string            repeatCountString    = simpleTrigger.repeatcount.TrimEmptyToNull();
                    string            repeatIntervalString = simpleTrigger.repeatinterval.TrimEmptyToNull();

                    int      repeatCount    = ParseSimpleTriggerRepeatCount(repeatCountString);
                    TimeSpan repeatInterval = repeatIntervalString == null ? TimeSpan.Zero : TimeSpan.FromMilliseconds(Convert.ToInt64(repeatIntervalString));

                    sched = SimpleScheduleBuilder.Create()
                            .WithInterval(repeatInterval)
                            .WithRepeatCount(repeatCount);

                    if (!simpleTrigger.misfireinstruction.IsNullOrWhiteSpace())
                    {
                        ((SimpleScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(simpleTrigger.misfireinstruction));
                    }
                }
                else if (triggerNode.Item is cronTriggerType)
                {
                    cronTriggerType cronTrigger    = (cronTriggerType)triggerNode.Item;
                    string          cronExpression = cronTrigger.cronexpression.TrimEmptyToNull();
                    string          timezoneString = cronTrigger.timezone.TrimEmptyToNull();

                    TimeZoneInfo tz = timezoneString != null?TimeZoneUtil.FindTimeZoneById(timezoneString) : null;

                    sched = CronScheduleBuilder.CronSchedule(cronExpression)
                            .InTimeZone(tz);

                    if (!cronTrigger.misfireinstruction.IsNullOrWhiteSpace())
                    {
                        ((CronScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(cronTrigger.misfireinstruction));
                    }
                }
                else if (triggerNode.Item is calendarIntervalTriggerType)
                {
                    calendarIntervalTriggerType calendarIntervalTrigger = (calendarIntervalTriggerType)triggerNode.Item;
                    string repeatIntervalString = calendarIntervalTrigger.repeatinterval.TrimEmptyToNull();

                    IntervalUnit intervalUnit   = ParseDateIntervalTriggerIntervalUnit(calendarIntervalTrigger.repeatintervalunit.TrimEmptyToNull());
                    int          repeatInterval = repeatIntervalString == null ? 0 : Convert.ToInt32(repeatIntervalString);

                    sched = CalendarIntervalScheduleBuilder.Create()
                            .WithInterval(repeatInterval, intervalUnit);

                    if (!calendarIntervalTrigger.misfireinstruction.IsNullOrWhiteSpace())
                    {
                        ((CalendarIntervalScheduleBuilder)sched).WithMisfireHandlingInstruction(ReadMisfireInstructionFromString(calendarIntervalTrigger.misfireinstruction));
                    }
                }
                else
                {
                    throw new SchedulerConfigException("Unknown trigger type in XML configuration");
                }

                IMutableTrigger trigger = (IMutableTrigger)TriggerBuilder.Create()
                                          .WithIdentity(triggerName, triggerGroup)
                                          .WithDescription(triggerDescription)
                                          .ForJob(triggerJobName, triggerJobGroup)
                                          .StartAt(triggerStartTime)
                                          .EndAt(triggerEndTime)
                                          .WithPriority(triggerPriority)
                                          .ModifiedByCalendar(triggerCalendarRef)
                                          .WithSchedule(sched)
                                          .Build();

                if (triggerNode.Item.jobdatamap != null && triggerNode.Item.jobdatamap.entry != null)
                {
                    foreach (entryType entry in triggerNode.Item.jobdatamap.entry)
                    {
                        string key   = entry.key.TrimEmptyToNull();
                        string value = entry.value.TrimEmptyToNull();
                        trigger.JobDataMap.Add(key, value);
                    }
                }

                if (Log.IsDebugEnabled())
                {
                    Log.Debug("Parsed trigger definition: " + trigger);
                }

                AddTriggerToSchedule(trigger);
            }
        }
Esempio n. 12
0
        /// <summary>
        /// 处理 即时采集任务
        /// </summary>
        /// <param name="tid"></param>
        /// <param name="dtuId">要采集的DTU</param>
        /// <param name="sensors">要采集的传感器,为空或Count=0时,指全部传感器。</param>
        /// <param name="consumer"></param>
        /// <param name="reactive">从数据库重新激活任务,默认=false</param>
        /// <returns> -1 </returns>
        public int ArrangeInstantTask(string tid, uint dtuId, IList <uint> sensors, TaskResultConsumer consumer, bool activeFromDB = false)
        {
            DtuNode dtu  = null;
            DACTask task = CreateInstantDACTask(tid, dtuId, sensors, consumer, activeFromDB);

            if (task == null)
            {
                return(-1); //无法创建任务.
            }
            dtu = _dtus[dtuId];

            bool ScheduleStarted = true;

            if (_schedule == null)
            {
                CreateSchedule(_dtus.Count);
                ScheduleStarted = false;
            }
            // Arrange an instant task to schedule
            string jobKey = GetJobKey(dtuId);
            JobKey jk     = new JobKey(jobKey, JobGroup);

            if (_schedule.GetJobDetail(jk) != null)
            {
                Log.DebugFormat("Task already exist? {0}", jk);
                return(-1);
            }
            IJobDetail job = JobBuilder.Create <DTUDacJob>()
                             .WithIdentity(jobKey, JobGroup)
                             .Build();

            AssignJobInfo(this, TaskType.INSTANT, job, tid, dtu, sensors, consumer, task.ID);
            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .WithIdentity(string.Format("{0}{1}", InstantTrigger, dtu.DtuId), JobGroup)
                                     .WithSimpleSchedule(x => x
                                                         .WithIntervalInSeconds(5000)
                                                         .WithRepeatCount(1))
                                     .StartNow()
                                     //.StartAt(DateBuilder.NextGivenMinuteDate(null, 10))
                                     .Build();

            _schedule.ScheduleJob(job, trigger);
            Console.WriteLine("Add job {1} {0}", DateTime.Now, job.Key.Name);
            if (!ScheduleStarted)
            {
                _schedule.Start();
            }
            Log.DebugFormat("Instance DAC Job created: {0}, task.ID={1}", jobKey, task.ID);
            //try
            //{
            //    _schedule.TriggerJob(jk);
            //}
            //catch (Exception ex)
            //{
            //    OnInstantTaskFinished(new FailedDACTaskResult(Errors.ERR_NOT_CONNECTED)
            //    {
            //        Task = task,
            //        Finished = DateTime.Now
            //    });
            //    Log.Error(ex.Message);
            //}
            return(task.ID);
        }
Esempio n. 13
0
        public async Task Init()
        {
            using (var client = DbFactory.GetClient())
            {
                var list = client.Queryable <ScheduleTask>().Where(t => t.IsEnable).ToList();
                if (list.Any())
                {
                    foreach (var scheduleTask in list)
                    {
                        scheduleTask.Status          = TaskRunningStatus.Running;
                        scheduleTask.StatusDesc      = "";
                        scheduleTask.JobKey          = Guid.NewGuid().ToString("N");
                        scheduleTask.JobGroup        = Guid.NewGuid().ToString("N");
                        scheduleTask.TriggerKey      = Guid.NewGuid().ToString("N");
                        scheduleTask.TriggerGroup    = Guid.NewGuid().ToString("N");
                        scheduleTask.LastEndTime     = null;
                        scheduleTask.LastStartTime   = null;
                        scheduleTask.LastSuccessTime = null;

                        var type = Type.GetType(scheduleTask.Type, false, true);
                        if (type == null)
                        {
                            scheduleTask.Status     = TaskRunningStatus.Error;
                            scheduleTask.StatusDesc = "反射类型失败";
                            continue;
                        }

                        var job = JobBuilder.Create(type)
                                  .WithIdentity(scheduleTask.JobKey, scheduleTask.JobGroup)
                                  .Build();

                        ITrigger trigger = null;
                        if (!string.IsNullOrEmpty(scheduleTask.Cron))
                        {
                            trigger = TriggerBuilder.Create()
                                      .WithIdentity(scheduleTask.TriggerKey, scheduleTask.TriggerGroup)
                                      .StartNow()
                                      .WithCronSchedule(scheduleTask.Cron)
                                      .Build();
                        }
                        else if (scheduleTask.Interval != null && scheduleTask.Interval.Value > 0)
                        {
                            trigger = TriggerBuilder.Create()
                                      .WithIdentity(scheduleTask.TriggerKey, scheduleTask.TriggerGroup)
                                      .StartNow()
                                      .WithSimpleSchedule(x => x
                                                          .WithIntervalInSeconds(scheduleTask.Interval.Value)
                                                          .RepeatForever())
                                      .Build();
                        }
                        else
                        {
                            scheduleTask.Status     = TaskRunningStatus.Error;
                            scheduleTask.StatusDesc = "找不到运行策略";
                            continue;
                        }

                        await _scheduler.ScheduleJob(job, trigger);
                    }

                    client.Updateable(list).ExecuteCommand();
                }

                await _scheduler.Start();
            }
        }
Esempio n. 14
0
        public async Task EnableJob(ScheduleTask scheduleTask)
        {
            if (!scheduleTask.TriggerKey.IsNullOrEmpty() && !scheduleTask.JobGroup.IsNullOrEmpty())
            {
                var isExist = await _scheduler.CheckExists(new TriggerKey(scheduleTask.TriggerKey, scheduleTask.TriggerGroup));

                if (isExist)
                {
                    await _scheduler.UnscheduleJob(new TriggerKey(scheduleTask.TriggerKey, scheduleTask.TriggerGroup));
                }
            }

            if (!scheduleTask.JobKey.IsNullOrEmpty() && !scheduleTask.JobGroup.IsNullOrEmpty())
            {
                var isExist = await _scheduler.CheckExists(new JobKey(scheduleTask.JobKey, scheduleTask.JobGroup));

                if (isExist)
                {
                    await _scheduler.DeleteJob(new JobKey(scheduleTask.JobKey, scheduleTask.JobGroup));
                }
            }

            scheduleTask.IsEnable     = true;
            scheduleTask.Status       = TaskRunningStatus.Running;
            scheduleTask.StatusDesc   = "";
            scheduleTask.JobKey       = Guid.NewGuid().ToString("N");
            scheduleTask.JobGroup     = Guid.NewGuid().ToString("N");
            scheduleTask.TriggerKey   = Guid.NewGuid().ToString("N");
            scheduleTask.TriggerGroup = Guid.NewGuid().ToString("N");

            var type = Type.GetType(scheduleTask.Type, false, true);

            if (type == null)
            {
                scheduleTask.IsEnable   = false;
                scheduleTask.Status     = TaskRunningStatus.Error;
                scheduleTask.StatusDesc = "反射类型失败";
                goto end;
            }

            var job = JobBuilder.Create(type)
                      .WithIdentity(scheduleTask.JobKey, scheduleTask.JobGroup)
                      .Build();

            ITrigger trigger = null;

            if (!string.IsNullOrEmpty(scheduleTask.Cron))
            {
                trigger = TriggerBuilder.Create()
                          .WithIdentity(scheduleTask.TriggerKey, scheduleTask.TriggerGroup)
                          .StartNow()
                          .WithCronSchedule(scheduleTask.Cron)
                          .Build();
            }
            else if (scheduleTask.Interval != null && scheduleTask.Interval.Value > 0)
            {
                trigger = TriggerBuilder.Create()
                          .WithIdentity(scheduleTask.TriggerKey, scheduleTask.TriggerGroup)
                          .StartNow()
                          .WithSimpleSchedule(x => x
                                              .WithIntervalInSeconds(scheduleTask.Interval.Value)
                                              .RepeatForever())
                          .Build();
            }
            else
            {
                scheduleTask.IsEnable   = false;
                scheduleTask.Status     = TaskRunningStatus.Error;
                scheduleTask.StatusDesc = "找不到运行策略";
                goto end;
            }

            await _scheduler.ScheduleJob(job, trigger);

end:
            {
                using (var client = DbFactory.GetClient())
                {
                    client.Updateable(scheduleTask).ExecuteCommand();
                }

                if (scheduleTask.Status == TaskRunningStatus.Error)
                {
                    throw new Exception(scheduleTask.StatusDesc);
                }
            }
        }
Esempio n. 15
0
        public async Task Start(string _configPath)
        {
            ConfigFile = _configPath;

            var list = new List <jobinfo>();

            if (sched != null)
            {
                stop();
                sched = null;
            }
            sched = await _schedulerFactory.GetScheduler();

            XmlDocument document = new XmlDocument();

            document.Load(ConfigFile);

            XmlNode node = document.SelectSingleNode("Jobs");

            if (node.ChildNodes.Count == 0)
            {
                Console.WriteLine("暂未有计划任务开启"); return;
            }

            foreach (XmlNode node2 in node.ChildNodes)
            {
                jobinfo item = new jobinfo
                {
                    name           = node2.Attributes["name"].Value,
                    type           = node2.Attributes["type"].Value,
                    CronExpression = node2.Attributes["CronExpression"].Value,
                    enabled        = bool.Parse(node2.Attributes["enabled"].Value),
                    runonce        = bool.Parse(node2.Attributes["runonce"].Value)
                };

                if (!item.enabled)
                {
                    continue;
                }

                list.Add(item);
                IJobDetail jobDetail = JobBuilder.Create(Type.GetType(item.type)).WithIdentity(item.name, item.name + "Group").Build();
                ITrigger   trigger   = null;

                if (!item.runonce)
                {
                    trigger = TriggerBuilder.Create().WithIdentity(item.name, item.name + "Group").WithCronSchedule(item.CronExpression).Build();
                }
                else
                {
                    trigger = TriggerBuilder.Create().WithIdentity(item.name, item.name + "Group").WithSimpleSchedule(x => x.WithIntervalInSeconds(1).WithRepeatCount(0)).Build();
                }
                await sched.ScheduleJob(jobDetail, trigger);
            }
            if (list.Count > 0)
            {
                await sched.Start();
            }
            else
            {
                Console.WriteLine("暂未有计划任务开启1");
            }
        }
Esempio n. 16
0
        public virtual void Run(bool inClearJobs, bool inScheduleJobs)
        {
            NameValueCollection properties = new NameValueCollection();

            properties["quartz.scheduler.instanceName"]    = "TestScheduler";
            properties["quartz.scheduler.instanceId"]      = "instance_one";
            properties["quartz.threadPool.type"]           = "Quartz.Simpl.SimpleThreadPool, Quartz";
            properties["quartz.threadPool.threadCount"]    = "5";
            properties["quartz.threadPool.threadPriority"] = "Normal";
            properties["quartz.jobStore.misfireThreshold"] = "60000";
            properties["quartz.jobStore.type"]             = "Quartz.Impl.AdoJobStore.JobStoreTX, Quartz";
            properties["quartz.jobStore.useProperties"]    = "false";
            properties["quartz.jobStore.dataSource"]       = "default";
            properties["quartz.jobStore.tablePrefix"]      = "QRTZ_";
            properties["quartz.jobStore.clustered"]        = "true";
            // if running MS SQL Server we need this
            properties["quartz.jobStore.lockHandler.type"] = "Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz";

            properties["quartz.dataSource.default.connectionString"] = "Server=(local);Database=quartz;Trusted_Connection=True;";
            properties["quartz.dataSource.default.provider"]         = "SqlServer-20";

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

            if (inClearJobs)
            {
                log.Warn("***** Deleting existing jobs/triggers *****");
                sched.Clear();
            }

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

            if (inScheduleJobs)
            {
                log.Info("------- Scheduling Jobs ------------------");

                string schedId = sched.SchedulerInstanceId;

                int count = 1;


                IJobDetail job = JobBuilder.NewJob <SimpleRecoveryJob>()
                                 .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                                 .RequestRecovery()                     // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                                 .Build();


                ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                         .WithIdentity("triger_" + count, schedId)
                                         .StartAt(DateBuilder.FutureDate(1, DateBuilder.IntervalUnit.Second))
                                         .WithSchedule(SimpleScheduleBuilder.Create()
                                                       .WithRepeatCount(20)
                                                       .WithInterval(TimeSpan.FromSeconds(5)))
                                         .Build();

                log.InfoFormat("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds);

                count++;


                job = JobBuilder.NewJob <SimpleRecoveryJob>()
                      .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                      .RequestRecovery()                     // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                      .Build();

                trigger = (ISimpleTrigger)TriggerBuilder.Create()
                          .WithIdentity("triger_" + count, schedId)
                          .StartAt(DateBuilder.FutureDate(2, DateBuilder.IntervalUnit.Second))
                          .WithSchedule(SimpleScheduleBuilder.Create()
                                        .WithRepeatCount(20)
                                        .WithInterval(TimeSpan.FromSeconds(5)))
                          .Build();

                log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds));
                sched.ScheduleJob(job, trigger);

                count++;


                job = JobBuilder.NewJob <SimpleRecoveryStatefulJob>()
                      .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                      .RequestRecovery()                     // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                      .Build();

                trigger = (ISimpleTrigger)TriggerBuilder.Create()
                          .WithIdentity("triger_" + count, schedId)
                          .StartAt(DateBuilder.FutureDate(1, DateBuilder.IntervalUnit.Second))
                          .WithSchedule(SimpleScheduleBuilder.Create()
                                        .WithRepeatCount(20)
                                        .WithInterval(TimeSpan.FromSeconds(3)))
                          .Build();

                log.Info(string.Format("{0} will run at: {1} and repeat: {2} times, every {3} seconds", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval.TotalSeconds));
                sched.ScheduleJob(job, trigger);

                count++;

                job = JobBuilder.NewJob <SimpleRecoveryJob>()
                      .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                      .RequestRecovery()                     // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                      .Build();

                trigger = (ISimpleTrigger)TriggerBuilder.Create()
                          .WithIdentity("triger_" + count, schedId)
                          .StartAt(DateBuilder.FutureDate(1, DateBuilder.IntervalUnit.Second))
                          .WithSchedule(SimpleScheduleBuilder.Create()
                                        .WithRepeatCount(20)
                                        .WithInterval(TimeSpan.FromSeconds(4)))
                          .Build();

                log.Info(string.Format("{0} will run at: {1} & repeat: {2}/{3}", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval));
                sched.ScheduleJob(job, trigger);

                count++;


                job = JobBuilder.NewJob <SimpleRecoveryJob>()
                      .WithIdentity("job_" + count, schedId) // put triggers in group named after the cluster node instance just to distinguish (in logging) what was scheduled from where
                      .RequestRecovery()                     // ask scheduler to re-execute this job if it was in progress when the scheduler went down...
                      .Build();

                trigger = (ISimpleTrigger)TriggerBuilder.Create()
                          .WithIdentity("triger_" + count, schedId)
                          .StartAt(DateBuilder.FutureDate(1, DateBuilder.IntervalUnit.Second))
                          .WithSchedule(SimpleScheduleBuilder.Create()
                                        .WithRepeatCount(20)
                                        .WithInterval(TimeSpan.FromMilliseconds(4500)))
                          .Build();

                log.Info(string.Format("{0} will run at: {1} & repeat: {2}/{3}", job.Key, trigger.GetNextFireTimeUtc(), trigger.RepeatCount, trigger.RepeatInterval));
                sched.ScheduleJob(job, trigger);
            }

            // jobs don't start firing until start() has been called...
            log.Info("------- Starting Scheduler ---------------");
            sched.Start();
            log.Info("------- Started Scheduler ----------------");

            log.Info("------- Waiting for one hour... ----------");

            Thread.Sleep(TimeSpan.FromHours(1));


            log.Info("------- Shutting Down --------------------");
            sched.Shutdown();
            log.Info("------- Shutdown Complete ----------------");
        }
Esempio n. 17
0
        public static async Task RunScheduler()
        {
            try
            {
                // Grab the Scheduler instance from the Factory
                NameValueCollection props = new NameValueCollection
                {
                    { "quartz.serializer.type", "binary" }
                };
                StdSchedulerFactory factory   = new StdSchedulerFactory(props);
                IScheduler          scheduler = await factory.GetScheduler();

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

                // Trigger the job to run now, and then every 40 seconds
                //ITrigger getCurrencyTrigger = TriggerBuilder.Create()
                //  .WithIdentity("GetCurrencyTrigger", "group1")
                //  .StartNow()
                //  .WithSimpleSchedule(x => x
                //      .WithIntervalInSeconds(30)
                //      .WithRepeatCount(2))
                //  .Build();

                //await scheduler.ScheduleJob(getCurrencyJob, getCurrencyTrigger);
                #endregion

                #region GetMarketJob
                //IJobDetail getMarketJob = JobBuilder.Create<GetMarketJob>()
                //    .WithIdentity("GetMarketJob", "group1")
                //    .Build();



                //ITrigger getMarketTrigger = TriggerBuilder.Create()
                //  .WithIdentity("GetMarketJob", "group1")
                //  .StartNow()
                //  .WithSimpleSchedule(x => x
                //      .WithIntervalInSeconds(30)
                //      .WithRepeatCount(4))
                //  .Build();

                //await scheduler.ScheduleJob(getMarketJob, getMarketTrigger);
                #endregion

                #region GetMarketHistoryJob
                IJobDetail getMarketHistoryJob = JobBuilder.Create <GetMarketHistoryJob>()
                                                 .WithIdentity("GetMarketHistory", "group1")
                                                 .Build();

                ITrigger getMarketHistoryTrigger = TriggerBuilder.Create()
                                                   .WithIdentity("GetMarketHistory", "group1")
                                                   .StartNow()
                                                   .WithSimpleSchedule(x => x
                                                                       .WithIntervalInSeconds(30)
                                                                       .WithRepeatCount(4))
                                                   .Build();

                await scheduler.ScheduleJob(getMarketHistoryJob, getMarketHistoryTrigger);

                #endregion

                // and start it off
                await scheduler.Start();

                // some sleep to show what's happening
                //await Task.Delay(TimeSpan.FromSeconds(60));

                // and last shut down the scheduler when you are ready to close your program
                //await scheduler.Shutdown();
            }
            catch (SchedulerException se)
            {
                await Console.Error.WriteLineAsync(se.ToString());
            }
        }
Esempio n. 18
0
        private static IEnumerable <(IJobDetail job, ITrigger trigger)> GetCronJobs(
            object service,
            TelemetryClient telemetryClient,
            ILogger logger)
        {
            Type type = service.GetType();

            foreach (MethodInfo method in type.GetRuntimeMethods())
            {
                if (method.IsStatic)
                {
                    continue;
                }

                if (method.GetParameters().Length > 1)
                {
                    continue;
                }

                if (method.ReturnType != typeof(Task))
                {
                    continue;
                }

                var attr = method.GetCustomAttribute <CronScheduleAttribute>();
                if (attr == null)
                {
                    continue;
                }

                IJobDetail job = JobBuilder.Create <MethodInvokingJob>()
                                 .WithIdentity(method.Name, type.Name)
                                 .UsingJobData(
                    new JobDataMap
                {
                    ["service"]         = service,
                    ["method"]          = method,
                    ["telemetryClient"] = telemetryClient
                })
                                 .Build();

                TimeZoneInfo scheduleTimeZone = TimeZoneInfo.Utc;

                try
                {
                    scheduleTimeZone = TimeZoneInfo.FindSystemTimeZoneById(attr.TimeZone);
                }
                catch (TimeZoneNotFoundException)
                {
                    logger.LogWarning(
                        "TimeZoneNotFoundException occurred for timezone string: {requestedTimeZoneName}",
                        attr.TimeZone);
                }
                catch (InvalidTimeZoneException)
                {
                    logger.LogWarning(
                        "InvalidTimeZoneException occurred for timezone string: {requestedTimeZoneName}",
                        attr.TimeZone);
                }

                ITrigger trigger = TriggerBuilder.Create()
                                   .WithIdentity(method.Name + "-Trigger", type.Name)
                                   .WithCronSchedule(attr.Schedule, schedule => schedule.InTimeZone(scheduleTimeZone))
                                   .StartNow()
                                   .Build();

                yield return(job, trigger);
            }
        }
Esempio n. 19
0
        private static async Task MainAsync()
        {
            NameValueCollection props = new NameValueCollection()
            {
                //{ "quartz.jobStore.type" ,"Quartz.Simpl.RAMJobStore,Quartz" },//默认使用内存存储
                { "quartz.jobStore.type", "Quartz.Impl.AdoJobStore.JobStoreTX,Quartz" },                                                                             //使用ado存储
                //{ "quartz.jobStore.driverDelegateType","Quartz.Impl.AdoJobStore.StdAdoDelegate,Quartz" },//默认ado委托
                { "quartz.jobStore.driverDelegateType", "Quartz.Impl.AdoJobStore.SqlServerDelegate,Quartz" },                                                        //sql server ado委托//性能更好
                //{ "quartz.jobStore.tablePrefix","QRTZ_"},//默认表前缀配置
                { "quartz.jobStore.dataSource", "NewcatsQuartzData" },                                                                                               //ado数据源名称配置
                { "quartz.dataSource.NewcatsQuartzData.connectionString", "Data Source = .; Initial Catalog =NewcatsDB20170627; User ID = sa; Password = 123456;" }, //链接字符串

                { "quartz.dataSource.NewcatsQuartzData.provider", "SqlServer" },                                                                                     //ado 驱动
                //目前支持一下驱动
                //SqlServer - .NET Framework 2.0的SQL Server驱动程序
                //OracleODP - Oracle的Oracle驱动程序
                //OracleODPManaged - Oracle的Oracle 11托管驱动程序
                //MySql - MySQL Connector / .NET
                //SQLite - SQLite ADO.NET Provider
                //SQLite-Microsoft - Microsoft SQLite ADO.NET Provider
                //Firebird - Firebird ADO.NET提供程序
                //Npgsql - PostgreSQL Npgsql

                { "quartz.jobStore.useProperties", "true" },//配置AdoJobStore以将字符串用作JobDataMap值(推荐)
                { "quartz.serializer.type", "json" }//ado 序列化策略//可选值为json/binary(推荐json)
            };

            StdSchedulerFactory factory   = new StdSchedulerFactory(props);
            IScheduler          scheduler = await factory.GetScheduler();//获取调度器

            //await scheduler.Start();//启动调度器

            IJobDetail job = JobBuilder.Create <HelloWorldJob>()
                             .StoreDurably()
                             .RequestRecovery()
                             .WithIdentity("job2", "group")
                             .Build();//定义一个job

            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .StartNow()                                   //立即开始
                                     .WithIdentity("t2", "group")
                                     .WithSimpleSchedule(x => x                    //使用简单调度器
                                                         .WithIntervalInSeconds(1) //每2秒执行一次
                                                         .RepeatForever())         //一直循环
                                     .Build();
            await scheduler.ScheduleJob(job, trigger);                             //等待执行任务

            //IDailyTimeIntervalTrigger dailyTrigger = (IDailyTimeIntervalTrigger)TriggerBuilder.Create()
            //    .StartNow()
            //    .WithDailyTimeIntervalSchedule(x => x
            //        .WithIntervalInSeconds(2)
            //        .WithRepeatCount(20))
            //    .Build();
            //await scheduler.ScheduleJob(job, dailyTrigger);

            //ICronTrigger cronTrigger = (ICronTrigger)TriggerBuilder.Create()
            //    .StartNow()
            //    .WithCronSchedule("* * * * * ?")
            //    .Build();
            //await scheduler.ScheduleJob(job, cronTrigger);

            //ISimpleTrigger simpleTrigger = (ISimpleTrigger)TriggerBuilder.Create()
            //    .StartNow()
            //    .WithSimpleSchedule(x => x
            //        .WithIntervalInMinutes(1)
            //        .RepeatForever())
            //    .EndAt(DateBuilder.DateOf(22, 0, 0))//晚上22点结束
            //    .Build();

            //ITrigger trigger1 = TriggerBuilder.Create()
            //    .WithCronSchedule("0 0/2 8-17 * * ?",//每天早上8点到下午5点建立一个触发器,每隔一分钟就会触发一次:
            //        x => x.WithMisfireHandlingInstructionDoNothing())//当一个持久的触发器因为调度器被关闭或者线程池中没有可用的线程而错过了激活时间时,不进行任何处理
            //    .Build();

            //ITrigger trigger2 = TriggerBuilder.Create()
            //    .WithSchedule(CronScheduleBuilder.DailyAtHourAndMinute(10, 42))//每天在上午10:42开始执行
            //    .Build();
        }
Esempio n. 20
0
        private void ScheduleWorkflow(Workflow wf)
        {
            try
            {
                if (wf.IsEnabled)
                {
                    if (wf.LaunchType == LaunchType.Startup)
                    {
                        wf.Start();
                    }
                    else if (wf.LaunchType == LaunchType.Periodic)
                    {
                        IDictionary <string, object> map = new Dictionary <string, object>();
                        map.Add("workflow", wf);

                        string     jobIdentity = "Workflow Job " + wf.Id;
                        IJobDetail jobDetail   = JobBuilder.Create <WorkflowJob>()
                                                 .WithIdentity(jobIdentity)
                                                 .SetJobData(new JobDataMap(map))
                                                 .Build();

                        ITrigger trigger = TriggerBuilder.Create()
                                           .ForJob(jobDetail)
                                           .WithSimpleSchedule(x => x.WithInterval(wf.Period).RepeatForever())
                                           .WithIdentity("Workflow Trigger " + wf.Id)
                                           .StartNow()
                                           .Build();

                        var jobKey = new JobKey(jobIdentity);
                        if (QuartzScheduler.CheckExists(jobKey).Result)
                        {
                            QuartzScheduler.DeleteJob(jobKey);
                        }

                        QuartzScheduler.ScheduleJob(jobDetail, trigger).Wait();
                    }
                    else if (wf.LaunchType == LaunchType.Cron)
                    {
                        IDictionary <string, object> map = new Dictionary <string, object>();
                        map.Add("workflow", wf);

                        string     jobIdentity = "Workflow Job " + wf.Id;
                        IJobDetail jobDetail   = JobBuilder.Create <WorkflowJob>()
                                                 .WithIdentity(jobIdentity)
                                                 .SetJobData(new JobDataMap(map))
                                                 .Build();

                        ITrigger trigger = TriggerBuilder.Create()
                                           .ForJob(jobDetail)
                                           .WithCronSchedule(wf.CronExpression)
                                           .WithIdentity("Workflow Trigger " + wf.Id)
                                           .StartNow()
                                           .Build();

                        var jobKey = new JobKey(jobIdentity);
                        if (QuartzScheduler.CheckExists(jobKey).Result)
                        {
                            QuartzScheduler.DeleteJob(jobKey);
                        }

                        QuartzScheduler.ScheduleJob(jobDetail, trigger).Wait();
                    }
                }
            }
            catch (Exception e)
            {
                Logger.ErrorFormat("An error occured while scheduling the workflow {0}: ", e, wf);
            }
        }
        public void TestOverwriteFlag()
        {
            // create temp file
            string tempFileName = XMLSchedulingDataProcessor.QuartzXmlFileName;

            using (TextWriter writer = new StreamWriter(tempFileName, false))
            {
                using (StreamReader reader = new StreamReader(ReadJobXmlFromEmbeddedResource("SimpleJobTrigger.xml")))
                {
                    writer.Write(reader.ReadToEnd());
                    writer.Flush();
                    writer.Close();
                }
            }

            IScheduler scheduler = null;

            try
            {
                StdSchedulerFactory factory = new StdSchedulerFactory();
                scheduler = StdSchedulerFactory.GetDefaultScheduler();

                // Let's setup a fixture job data that we know test is not going modify it.
                IJobDetail job = JobBuilder.Create <NoOpJob>()
                                 .WithIdentity("job1").UsingJobData("foo", "dont_chg_me").Build();
                ITrigger trigger = TriggerBuilder.Create().WithIdentity("job1").WithSchedule(SimpleScheduleBuilder.RepeatHourlyForever()).Build();
                scheduler.ScheduleJob(job, trigger);

                XMLSchedulingDataProcessor processor = new XMLSchedulingDataProcessor(new SimpleTypeLoadHelper());
                try
                {
                    processor.ProcessFileAndScheduleJobs(scheduler, false);
                    Assert.Fail("OverWriteExisting flag didn't work. We should get Exception when overwrite is set to false.");
                }
                catch (ObjectAlreadyExistsException)
                {
                    // This is expected. Do nothing.
                }

                // We should still have what we start with.
                Assert.AreEqual(1, scheduler.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("DEFAULT")).Count);
                Assert.AreEqual(1, scheduler.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("DEFAULT")).Count);

                job = scheduler.GetJobDetail(JobKey.Create("job1"));
                String fooValue = job.JobDataMap.GetString("foo");
                Assert.AreEqual("dont_chg_me", fooValue);
            }
            finally
            {
                if (File.Exists(tempFileName))
                {
                    File.Delete(tempFileName);
                }

                // shutdown scheduler
                if (scheduler != null)
                {
                    scheduler.Shutdown();
                }
            }
        }
Esempio n. 22
0
        public virtual async Task Run()
        {
            log.Info("------- Initializing ----------------------");

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

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

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

            // get a "nice round" time a few seconds in the future...

            DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 15);

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

            ISimpleTrigger trigger = (ISimpleTrigger)TriggerBuilder.Create()
                                     .WithIdentity("trigger1", "group1")
                                     .StartAt(startTime)
                                     .WithSimpleSchedule(x => x.WithIntervalInSeconds(5).RepeatForever())
                                     .Build();

            DateTimeOffset ft = await sched.ScheduleJob(job, trigger);

            log.Info($"{job.Key} will run at: {ft:r} and repeat: {trigger.RepeatCount} times, every {trigger.RepeatInterval.TotalSeconds} seconds");

            // start up the scheduler (jobs do not start to fire until
            // the scheduler has been started)
            await sched.Start();

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

            log.Info("------- Starting loop to interrupt job every 7 seconds ----------");
            for (int i = 0; i < 50; i++)
            {
                try
                {
                    await Task.Delay(TimeSpan.FromSeconds(7));

                    // tell the scheduler to interrupt our job
                    await sched.Interrupt(job.Key);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }

            log.Info("------- Shutting Down ---------------------");

            await sched.Shutdown(true);

            log.Info("------- Shutdown Complete -----------------");
            SchedulerMetaData metaData = await sched.GetMetaData();

            log.Info($"Executed {metaData.NumberOfJobsExecuted} jobs.");
        }
Esempio n. 23
0
        static async Task NoUpdateSch()
        {
            try
            {
                IScheduler sched = await Global.GetScheduler();

                if (!sched.IsStarted)
                {
                    await sched.Start();
                }

                await sched.Clear();

                TaskBuss        taskBuss = new TaskBuss();
                List <TaskItem> list     = taskBuss.InitTask();

                foreach (TaskItem item in list)
                {
                    JobDataMap keyValues = new JobDataMap();
                    Type       t         = item.GetType();
                    foreach (FieldInfo fieldInfo in t.GetFields())
                    {
                        keyValues.Add(fieldInfo.Name, fieldInfo.GetValue(item));
                    }
                    IJobDetail job;
                    if (item.taskType == "0")
                    {
                        job = JobBuilder.Create <TaskDBJob>()
                              .WithIdentity(item.taskCode, "BussDB")
                              .SetJobData(keyValues)
                              .Build();
                    }
                    else
                    {
                        job = JobBuilder.Create <TaskLoopJob>()
                              .WithIdentity(item.taskCode, "BussLoop")
                              .SetJobData(keyValues)
                              .Build();
                    }
                    if (item.triggerType == "0")
                    {
                        ITrigger trigger = TriggerBuilder.Create()
                                           .WithIdentity(item.taskCode + "Trigger", "BussTrig")
                                           .StartNow()
                                           .WithSimpleSchedule(x => x
                                                               .WithIntervalInSeconds(item.interval)
                                                               .RepeatForever())
                                           .Build();
                        await sched.ScheduleJob(job, trigger);
                    }
                    else
                    {
                        ICronTrigger cronTrigger = (ICronTrigger)TriggerBuilder.Create()
                                                   .WithCronSchedule(item.cronExpression)
                                                   .Build();
                        await sched.ScheduleJob(job, cronTrigger);
                    }
                    Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "> " + "已启动任务:" + item.taskCode);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm") + "> " + ex.StackTrace);
            }
        }
Esempio n. 24
0
        public async Task TestBasicStorageFunctions()
        {
            NameValueCollection config = new NameValueCollection();

            config["quartz.scheduler.instanceName"] = "SchedulerTest_Scheduler";
            config["quartz.scheduler.instanceId"]   = "AUTO";
            config["quartz.threadPool.threadCount"] = "2";
            config["quartz.threadPool.type"]        = "Quartz.Simpl.SimpleThreadPool, Quartz";
            config["quartz.serializer.type"]        = TestConstants.DefaultSerializerType;
            IScheduler sched = await new StdSchedulerFactory(config).GetScheduler();

            // test basic storage functions of scheduler...

            IJobDetail job = JobBuilder.Create()
                             .OfType <TestJob>()
                             .WithIdentity("j1")
                             .StoreDurably()
                             .Build();

            var exists = await sched.CheckExists(new JobKey("j1"));

            Assert.IsFalse(exists, "Unexpected existence of job named 'j1'.");

            await sched.AddJob(job, false);

            exists = await sched.CheckExists(new JobKey("j1"));

            Assert.IsTrue(exists, "Expected existence of job named 'j1' but checkExists return false.");

            job = await sched.GetJobDetail(new JobKey("j1"));

            Assert.IsNotNull(job, "Stored job not found!");

            await sched.DeleteJob(new JobKey("j1"));

            ITrigger trigger = TriggerBuilder.Create()
                               .WithIdentity("t1")
                               .ForJob(job)
                               .StartNow()
                               .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5))
                               .Build();

            exists = await sched.CheckExists(new TriggerKey("t1"));

            Assert.IsFalse(exists, "Unexpected existence of trigger named '11'.");

            await sched.ScheduleJob(job, trigger);

            exists = await sched.CheckExists(new TriggerKey("t1"));

            Assert.IsTrue(exists, "Expected existence of trigger named 't1' but checkExists return false.");

            job = await sched.GetJobDetail(new JobKey("j1"));

            Assert.IsNotNull(job, "Stored job not found!");

            trigger = await sched.GetTrigger(new TriggerKey("t1"));

            Assert.IsNotNull(trigger, "Stored trigger not found!");

            job = JobBuilder.Create()
                  .OfType <TestJob>()
                  .WithIdentity("j2", "g1")
                  .Build();

            trigger = TriggerBuilder.Create()
                      .WithIdentity("t2", "g1")
                      .ForJob(job)
                      .StartNow()
                      .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5))
                      .Build();

            await sched.ScheduleJob(job, trigger);

            job = JobBuilder.Create()
                  .OfType <TestJob>()
                  .WithIdentity("j3", "g1")
                  .Build();

            trigger = TriggerBuilder.Create()
                      .WithIdentity("t3", "g1")
                      .ForJob(job)
                      .StartNow()
                      .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5))
                      .Build();

            await sched.ScheduleJob(job, trigger);

            var jobGroups = await sched.GetJobGroupNames();

            var triggerGroups = await sched.GetTriggerGroupNames();

            Assert.AreEqual(2, jobGroups.Count, "Job group list size expected to be = 2 ");
            Assert.AreEqual(2, triggerGroups.Count, "Trigger group list size expected to be = 2 ");

            ISet <JobKey> jobKeys = await sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(JobKey.DefaultGroup));

            ISet <TriggerKey> triggerKeys = await sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals(TriggerKey.DefaultGroup));

            Assert.AreEqual(1, jobKeys.Count, "Number of jobs expected in default group was 1 ");
            Assert.AreEqual(1, triggerKeys.Count, "Number of triggers expected in default group was 1 ");

            jobKeys = await sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("g1"));

            triggerKeys = await sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("g1"));

            Assert.AreEqual(2, jobKeys.Count, "Number of jobs expected in 'g1' group was 2 ");
            Assert.AreEqual(2, triggerKeys.Count, "Number of triggers expected in 'g1' group was 2 ");

            TriggerState s = await sched.GetTriggerState(new TriggerKey("t2", "g1"));

            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            await sched.PauseTrigger(new TriggerKey("t2", "g1"));

            s = await sched.GetTriggerState(new TriggerKey("t2", "g1"));

            Assert.AreEqual(TriggerState.Paused, s, "State of trigger t2 expected to be PAUSED ");

            await sched.ResumeTrigger(new TriggerKey("t2", "g1"));

            s = await sched.GetTriggerState(new TriggerKey("t2", "g1"));

            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            ISet <string> pausedGroups = await sched.GetPausedTriggerGroups();

            Assert.AreEqual(0, pausedGroups.Count, "Size of paused trigger groups list expected to be 0 ");

            await sched.PauseTriggers(GroupMatcher <TriggerKey> .GroupEquals("g1"));

            // test that adding a trigger to a paused group causes the new trigger to be paused also...
            job = JobBuilder.Create()
                  .OfType <TestJob>()
                  .WithIdentity("j4", "g1")
                  .Build();

            trigger = TriggerBuilder.Create()
                      .WithIdentity("t4", "g1")
                      .ForJob(job)
                      .StartNow()
                      .WithSimpleSchedule(x => x.RepeatForever().WithIntervalInSeconds(5))
                      .Build();

            await sched.ScheduleJob(job, trigger);

            pausedGroups = await sched.GetPausedTriggerGroups();

            Assert.AreEqual(1, pausedGroups.Count, "Size of paused trigger groups list expected to be 1 ");

            s = await sched.GetTriggerState(new TriggerKey("t2", "g1"));

            Assert.AreEqual(TriggerState.Paused, s, "State of trigger t2 expected to be PAUSED ");

            s = await sched.GetTriggerState(new TriggerKey("t4", "g1"));

            Assert.AreEqual(TriggerState.Paused, s, "State of trigger t4 expected to be PAUSED");

            await sched.ResumeTriggers(GroupMatcher <TriggerKey> .GroupEquals("g1"));

            s = await sched.GetTriggerState(new TriggerKey("t2", "g1"));

            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            s = await sched.GetTriggerState(new TriggerKey("t4", "g1"));

            Assert.AreEqual(TriggerState.Normal, s, "State of trigger t2 expected to be NORMAL ");

            pausedGroups = await sched.GetPausedTriggerGroups();

            Assert.AreEqual(0, pausedGroups.Count, "Size of paused trigger groups list expected to be 0 ");

            Assert.IsFalse(await sched.UnscheduleJob(new TriggerKey("foasldfksajdflk")), "Scheduler should have returned 'false' from attempt to unschedule non-existing trigger. ");

            Assert.IsTrue(await sched.UnscheduleJob(new TriggerKey("t3", "g1")), "Scheduler should have returned 'true' from attempt to unschedule existing trigger. ");

            jobKeys = await sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals("g1"));

            triggerKeys = await sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals("g1"));

            Assert.AreEqual(2, jobKeys.Count, "Number of jobs expected in 'g1' group was 1 "); // job should have been deleted also, because it is non-durable
            Assert.AreEqual(2, triggerKeys.Count, "Number of triggers expected in 'g1' group was 1 ");

            Assert.IsTrue(await sched.UnscheduleJob(new TriggerKey("t1")), "Scheduler should have returned 'true' from attempt to unschedule existing trigger. ");

            jobKeys = await sched.GetJobKeys(GroupMatcher <JobKey> .GroupEquals(JobKey.DefaultGroup));

            triggerKeys = await sched.GetTriggerKeys(GroupMatcher <TriggerKey> .GroupEquals(TriggerKey.DefaultGroup));

            Assert.AreEqual(1, jobKeys.Count, "Number of jobs expected in default group was 1 "); // job should have been left in place, because it is non-durable
            Assert.AreEqual(0, triggerKeys.Count, "Number of triggers expected in default group was 0 ");

            await sched.Shutdown();
        }
        public virtual void Run()
        {
            ILog log = LogManager.GetLogger(typeof(CronTriggerExample));

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

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

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

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

            // jobs can be scheduled before sched.start() has been called

            // job 1 will run every 20 seconds

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

            ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                                   .WithIdentity("trigger1", "group1")
                                   .WithCronSchedule("0/20 * * * * ?")
                                   .Build();

            DateTimeOffset ft = sched.ScheduleJob(job, trigger);

            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 2 will run every other minute (at 15 seconds past the minute)
            job = JobBuilder.Create <SimpleJob>()
                  .WithIdentity("job2", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger2", "group1")
                      .WithCronSchedule("15 0/2 * * * ?")
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 3 will run every other minute but only between 8am and 5pm
            job = JobBuilder.Create <SimpleJob>()
                  .WithIdentity("job3", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger3", "group1")
                      .WithCronSchedule("0 0/2 8-17 * * ?")
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 4 will run every three minutes but only between 5pm and 11pm
            job = JobBuilder.Create <SimpleJob>()
                  .WithIdentity("job4", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger4", "group1")
                      .WithCronSchedule("0 0/3 17-23 * * ?")
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 5 will run at 10am on the 1st and 15th days of the month
            job = JobBuilder.Create <SimpleJob>()
                  .WithIdentity("job5", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger5", "group1")
                      .WithCronSchedule("0 0 10am 1,15 * ?")
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 6 will run every 30 seconds but only on Weekdays (Monday through Friday)
            job = JobBuilder.Create <SimpleJob>()
                  .WithIdentity("job6", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger6", "group1")
                      .WithCronSchedule("0,30 * * ? * MON-FRI")
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

            // job 7 will run every 30 seconds but only on Weekends (Saturday and Sunday)
            job = JobBuilder.Create <SimpleJob>()
                  .WithIdentity("job7", "group1")
                  .Build();

            trigger = (ICronTrigger)TriggerBuilder.Create()
                      .WithIdentity("trigger7", "group1")
                      .WithCronSchedule("0,30 * * ? * SAT,SUN")
                      .Build();

            ft = sched.ScheduleJob(job, trigger);
            log.Info(job.Key + " has been scheduled to run at: " + ft
                     + " and repeat based on expression: "
                     + trigger.CronExpressionString);

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

            // All of the jobs have been added to the scheduler, but none of the
            // jobs
            // will run until the scheduler has been started
            sched.Start();

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

            log.Info("------- Waiting five minutes... ------------");
            try
            {
                // wait five minutes to show jobs
                Thread.Sleep(300 * 1000);
                // executing...
            }
            catch (ThreadInterruptedException)
            {
            }

            log.Info("------- Shutting Down ---------------------");

            sched.Shutdown(true);

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

            SchedulerMetaData metaData = sched.GetMetaData();

            log.Info(string.Format("Executed {0} jobs.", metaData.NumberOfJobsExecuted));
        }
Esempio n. 26
0
        protected override void InitScheduler(IScheduler scheduler)
        {
            // construct job info
            var jobDetail = JobBuilder.Create <HelloJob>()
                            .WithIdentity("myJob")
                            .StoreDurably()
                            .Build();

            // fire every minute
            var trigger = TriggerBuilder.Create()
                          .WithIdentity("myTrigger")
                          .StartNow()
                          .WithSimpleSchedule(x => x.WithIntervalInMinutes(1).RepeatForever())
                          .Build();

            scheduler.ScheduleJob(jobDetail, trigger);

            // construct job info
            var jobDetail2 = JobBuilder.Create <HelloJob>()
                             .WithIdentity("myJob2")
                             .Build();

            // fire every 3 minutes
            var trigger2 = TriggerBuilder.Create()
                           .WithIdentity("myTrigger2")
                           .StartNow()
                           .WithSimpleSchedule(x => x.WithIntervalInMinutes(3))
                           .Build();

            scheduler.ScheduleJob(jobDetail2, trigger2);

            var trigger3 = TriggerBuilder.Create()
                           .WithIdentity("myTrigger3")
                           .ForJob(jobDetail2)
                           .StartNow()
                           .WithSimpleSchedule(x => x.WithIntervalInSeconds(2).RepeatForever())
                           //.WithSimpleSchedule(x => x.WithIntervalInMinutes(5).RepeatForever())
                           .Build();

            scheduler.ScheduleJob(trigger3);

            // construct job info
            var jobDetail4 = JobBuilder.Create <HelloJob>()
                             .WithIdentity("myJob4", "MyOwnGroup")
                             .Build();

            jobDetail4.JobDataMap.Add("key1", "value1");
            jobDetail4.JobDataMap.Add("key2", "value2");
            jobDetail4.JobDataMap.Add("key3", 1L);
            jobDetail4.JobDataMap.Add("key4", 1d);

            // fire every hour
            ITrigger trigger4 = TriggerBuilder.Create()
                                .WithIdentity("myTrigger4", jobDetail4.Key.Group)
                                .StartNow()
                                .WithSimpleSchedule(x => x.WithIntervalInMinutes(1))
                                .Build();

            ITrigger trigger5 = TriggerBuilder.Create()
                                .WithIdentity("myTrigger5", jobDetail4.Key.Group)
                                .StartNow()
                                .WithCronSchedule("0 0/5 * * * ?")
                                .Build();


            scheduler.ScheduleJob(jobDetail4, new HashSet <ITrigger>(new[] { trigger4, trigger5 }), false);
//            scheduler.ScheduleJob(jobDetail4, trigger5);

            scheduler.PauseJob(new JobKey("myJob4", "MyOwnGroup"));
            scheduler.PauseTrigger(new TriggerKey("myTrigger3", "DEFAULT"));
        }
Esempio n. 27
0
        public Task HandleExceptionAsync(JobBuilder jobBuilder, Exception jobException, CancellationToken cancellationToken = default)
        {
            _logger.LogError(jobException, "An error occurred while executing a job.");

            return(Task.CompletedTask);
        }
Esempio n. 28
0
        /// <summary>
        /// 注册方法
        /// </summary>
        /// <param name="TaskName"></param>
        /// <param name="TaskGroup"></param>
        /// <returns></returns>
        public override IJobDetail CreateJobDetail(string TaskGroup)
        {
            IJobDetail simpleJob = JobBuilder.Create <Job>().WithIdentity(TaskName, TaskGroup).Build();

            return(simpleJob);
        }
Esempio n. 29
0
        public static void Run()
        {
            Task.Run(async() =>
            {
                var schedulerFactory = new StdSchedulerFactory();
                var _scheduler       = await schedulerFactory.GetScheduler();


                var job = JobBuilder.Create <QuartzJob>()
                          .WithIdentity("1234")
                          .Build();

                var builder = TriggerBuilder.Create()
                              .WithIdentity("1234")
                              .WithCronSchedule("0/3 * * * * ? ", b =>
                {
                    // if startAt < now , do nothing about the misfired trigger
                    b.WithMisfireHandlingInstructionDoNothing();
                    b.InTimeZone(TimeZoneInfo.Local);
                })
                              .EndAt(DateTimeOffset.MaxValue)
                              //.StartAt(startAt.Value)
                              //.StartNow()
                              .StartAt(DateTimeOffset.UtcNow.AddSeconds(-20))
                ;

                var trigger = builder.Build();
                await _scheduler.Start();
                await _scheduler.ScheduleJob(job, trigger);
            });
            Console.ReadLine();

            CronExpression aa = new CronExpression("0 0 0 * 1,3 ?");

            Console.WriteLine(aa.CronExpressionString);


            string cronTest = "* 40 10/2 * * ?";

            Console.WriteLine(CronExpression.IsValidExpression(cronTest));

            string         cronExpressionInBeijingTime = "* 40 10/2 * * ?";
            CronExpression cronExpression = new CronExpression(cronExpressionInBeijingTime);

            cronExpression.TimeZone = TimeZoneInfo.Local;

            DateTimeOffset?nextUtcTime   = cronExpression.GetNextValidTimeAfter(DateTimeOffset.UtcNow);
            DateTimeOffset nextLocalTime = TimeZoneInfo.ConvertTime(nextUtcTime.Value, TimeZoneInfo.Local);



            Console.WriteLine(cronExpressionInBeijingTime);


            Console.WriteLine(nextUtcTime);
            Console.WriteLine(nextLocalTime);

            CronExpression utcExpression = new CronExpression(cronExpressionInBeijingTime);

            var summ = utcExpression.GetExpressionSummary();

            //  cronExpression.TimeZone = TimeZoneInfo.Utc;
            Console.WriteLine(cronExpression.CronExpressionString);



            string         cor  = "36 24 15 L /1 ?";
            CronExpression exer = new CronExpression(cor);
            DateTimeOffset?af   = DateTimeOffset.Now;

            for (int i = 0; i < 5; i++)
            {
                af = exer.GetNextValidTimeAfter(af.Value);
                Console.WriteLine(af);
            }
        }
Esempio n. 30
0
 private async Task<Job> ConstructAndRegister(JobShop jobShop, JobBuilder builder)
 {
     var createdJob = jobShop.Construct(builder);
     return await manager.RegisterJob(createdJob);
 }
Esempio n. 31
0
        /// <summary>
        /// 执行JOB 用于检查Job_Info表
        /// </summary>
        /// <param name="context"></param>
        public void Execute(IJobExecutionContext context)
        {
            Log4NetHelper.Info("开始获取JobInfo", logger: logger);
            try
            {
                List <Job_Info> jobList = new JobInfoBLL().GetJobList();
                if (jobList != null && jobList.Count > 0)
                {
                    JobKey jobKey = null;
                    foreach (var jobinfo in jobList)
                    {
                        jobKey = new JobKey(jobinfo.Job_name + JobConfig.JOBKEY_NAMEEND, "group1");
                        //只有正常执行状态的Job才添加到调度器中
                        if (!JobConfig.scheduler.CheckExists(jobKey) && jobinfo.Job_state == 0)
                        {
                            IJobDetail job = JobBuilder.Create <RunTaskDLLJob>().WithIdentity(jobKey).Build();

                            //创建触发器
                            TriggerBuilder tb = TriggerBuilder.Create()
                                                .WithIdentity(jobinfo.Job_name + JobConfig.JOBTRIGGER_NAMEEND, "group1");
                            if (!string.IsNullOrEmpty(jobinfo.Job_corn))
                            {
                                tb.WithCronSchedule(jobinfo.Job_corn); //执行corn表达式
                            }
                            if (jobinfo.Job_execount > 0)              //如果执行固定的次数
                            {
                                tb.WithSimpleSchedule(a => a.WithRepeatCount(jobinfo.Job_execount));
                            }

                            if (jobinfo.Job_starttime != null && jobinfo.Job_starttime > DateTime.Now)//设置Job启动时间
                            {
                                tb.StartAt(jobinfo.Job_starttime);
                            }
                            else
                            {
                                tb.StartNow();
                            }

                            ITrigger trigger = tb.Build();
                            //传递参数
                            job.JobDataMap.Add(jobKey.Name, jobinfo.Id);

                            JobConfig.scheduler.ScheduleJob(job, trigger);

                            Log4NetHelper.Info(string.Format("加入Job:{0}成功", jobKey.Name), logger: logger);
                        }
                        else if (JobConfig.scheduler.CheckExists(jobKey))
                        {
                            if (jobinfo.Job_state == 2 || jobinfo.Job_state == 3)
                            {
                                JobConfig.scheduler.PauseJob(jobKey);
                                Log4NetHelper.Info(string.Format("暂停Job:{0}成功", jobKey.Name), logger: logger);
                            }
                            else if (jobinfo.Job_state == 4)
                            {
                                JobConfig.scheduler.DeleteJob(jobKey);
                                Log4NetHelper.Info(string.Format("删除Job:{0}成功", jobKey.Name), logger: logger);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Log4NetHelper.Info(string.Format("LoopJob异常:{0},{1},{2}", ex.Message, ex.InnerException, ex.StackTrace), logger: logger);
            }
            Log4NetHelper.Info("结束获取JobInfo", logger: logger);
        }