public async Task <ActionResult> InterruptJob(string name, string group, string instance)
        {
            TempData["ErrorDetails"] = "";
            try
            {
                IScheduler scheduler = await QuartzHelper.GetScheduler();

                //scheduler.Interrupt(new JobKey(name, group));
                await scheduler.Interrupt(instance);
            }
            catch (Exception ex)
            {
                TempData["ErrorDetails"] = ex.Message;
                // give up
            }

            return(RedirectToAction("Index"));
        }
        public DataRes <bool> Execute(int id)
        {
            var res = new DataRes <bool>()
            {
                code = ResCode.Success, data = true
            };

            using (var uow = _uowProvider.CreateUnitOfWork())
            {
                var repository = uow.GetRepository <ResSchedule>();
                var model      = repository.Get(id);
                //var scheduleEntity = Mapper<ResSchedule, ScheduleEntity>.Map(model);
                ////给IJob设置参数
                //scheduleEntity.Agrs = new Dictionary<string, object> { { "orderId", id } };
                //ScheduleManage.Instance.AddScheduleList(scheduleEntity);
                //// 运行任务调度
                BaseQuartzNetResult result;
                result = QuartzHelper.ResumeScheduleAsync(model).Result;
                //if (model.TriggerType == 0)
                //{
                //    result = _schedulerCenter.RunScheduleJob<ScheduleManage, SubmitJobTask>(model.JobGroup, model.JobName).Result;
                //}
                //else
                //{
                //    result = _schedulerCenter.RunScheduleJob<ScheduleManage>(model.JobGroup, model.JobName).Result;
                //}
                Console.Out.WriteLineAsync("任务执行状态:" + result.Msg);
                if (result.Code == 1000)
                {
                    model.JobStatus = 1;
                    model.WriteDate = DateTime.Now;
                    var t10 = repository.Update(model);
                    res.msg = result.Msg;
                    logger.Info($"任务执行中:{model.JobGroup}-{model.JobName},{result.Msg}");
                }
                else
                {
                    res.code = ResCode.Error;
                    res.msg  = result.Msg;
                    logger.Error($"任务执行失败:{model.JobGroup}-{model.JobName},{result.Msg}");
                }
            }
            return(res);
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        protected void Application_Start()
        {
            //webapi 配置
            GlobalConfiguration.Configure(WebApiConfig.Register);
            //RouteConfig.RegisterRoutes(RouteTable.Routes);
            //注册错误异常
            GlobalConfiguration.Configuration.Filters.Add(new ExceptionAttribute());
            //注册参数验证
            GlobalConfiguration.Configuration.Filters.Add(new ValidParameterAttribute());
            //注册认证
            //GlobalConfiguration.Configuration.Filters.Add(new AuthenticationAttribute());

            //上传文件服务
            //QueueHelper<UploadFileObj>.Register(UploadFileAction.UploadFile);
            //QueueHelper<UploadFileObj>.Start();

            QuartzHelper.CreateScheduler().GetAwaiter().GetResult();
            QuartzHelper.RegisterJob <SyncMessageJob>("/5 * * ? * *", "wechat").GetAwaiter().GetResult();
        }
Example #4
0
        public JsonResult DeleteJob(List <JobDeleteViewModel> idList)
        {
            var result = new ResponseResult();

            try
            {
                foreach (var item in idList)
                {
                    QuartzHelper.DeleteJob(item.JobName, item.GroupName).GetAwaiter();
                }
                result.success = true;
            }
            catch (Exception ex)
            {
                result.success = false;
                result.message = ex.Message;
            }
            return(Json(result));
        }
Example #5
0
        /// <summary>
        /// 启动应用程序
        /// </summary>
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            // 启动的时候清除全部缓存
            ICache cache = CacheFactory.CaChe();

            cache.RemoveAll(6);

            WfJobScheduler.Start();
            QuartzHelper.InitJob();
            #region 队列处理示例
            //ThreadPool.QueueUserWorkItem(o =>
            //{
            //    while (true)
            //    {
            //        if (cache.ListLength("TicketQueue") > 50)
            //        {
            //            cache.Remove("TicketQueue");
            //        }
            //        if (cache.ListLength("BuyQueue") > 0)
            //        {
            //            Random rd = new Random();
            //            int carNo = rd.Next(10, 18);
            //            string[] seat = { "A", "B", "C", "D", "E", "F" };
            //            Buyer buyer = cache.ListRightPop<Buyer>("BuyQueue");
            //            //写入车票队列
            //            cache.ListLeftPush("TicketQueue", new { name = buyer.name, id = buyer.id, ticketdate = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd HH:mm"), code = carNo + "车" + (carNo / 2).ToString() + seat[rd.Next(0, 6)] });
            //            Thread.Sleep(1000);//假装处理这个业务花了1毫秒
            //        }
            //        else
            //        {
            //            Thread.Sleep(3000);//防止CPU空转
            //        }

            //        if (cache.ListLength("BuyQueue") > 10)
            //        {
            //            cache.Remove("BuyQueue");
            //        }
            //    }
            //});
        }
Example #6
0
        public JsonResult NextFireTime()
        {
            string cronExpressionString = Request.Params["CronExpression"].ToString();

            try
            {
                var result = QuartzHelper.GetNextFireTime(cronExpressionString, 5);

                JavaScriptSerializer js = new JavaScriptSerializer();

                string msg = js.Serialize(result);

                return(Json(new { result = true, msg = msg }));
            }
            catch
            {
                return(Json(new { result = false, msg = "" }));
            }
        }
Example #7
0
        static void Main(string[] args)
        {
            AdminRun.Run();
            //1.MEF初始化
            MefConfig.Init();

            //2.
            ConfigInit.InitConfig();

            //3.系统参数配置初始化
            ConfigManager configManager = MefConfig.TryResolve <ConfigManager>();

            configManager.Init();


            QuartzHelper.InitScheduler();
            QuartzHelper.StartScheduler();
            try
            {
                //启动站点
                using (NancyHost host = Startup.Start(SystemConfig.WebPort))
                {
                    //调用系统默认的浏览器
                    string url = string.Format("http://127.0.0.1:{0}", SystemConfig.WebPort);
                    Process.Start(url);
                    Console.WriteLine("系统监听站点地址:{0}", url);
                    Console.WriteLine("程序已启动,按任意键退出");
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }



            //ParseExpressCode();
            //ExpressUtil.HandleProecssInfo("");
            //MessageHelper.SendMessage(new Guid("6282AA73-2A58-E511-8D70-00155D0C740D"));
            //new Ywdsoft.Task.TaskSet.SendMessageJob().Execute(null);
            Console.Read();
        }
Example #8
0
 public void StopJob(int jobId)
 {
     using (var ctx = new BatchJobDbContext())
     {
         try
         {
             var job = ctx.Jobs.Find(jobId);
             if (job != null)
             {
                 var scheduler = QuartzHelper.GetScheduler(job.JobGroup.Scheduler.Name, job.JobGroup.Scheduler.ThreadPoolSize, (int)job.JobGroup.Scheduler.Priority);
                 scheduler.PauseJob(job.Code, job.JobGroup.Name);
                 job.StopJob();
                 ctx.SaveChanges();
             }
         }
         catch (Exception ex)
         {
             throw ex;
         }
     }
 }
Example #9
0
        protected override void OnStart(string[] args)
        {
            DebuggableAttribute att = System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttribute <DebuggableAttribute>();

            if (att.IsJITTrackingEnabled)
            {
                //Debug模式才让线程停止10s,方便附加到进程调试
                Thread.Sleep(10000);
            }
            //配置信息读取
            ConfigInit.InitConfig();
            QuartzHelper.InitScheduler();
            QuartzHelper.StartScheduler();

            // 保持web服务运行
            ThreadPool.QueueUserWorkItem((o) =>
            {
                //启动站点
                Startup.Start(SysConfig.WebPort);
            });
        }
Example #10
0
 protected override ITrigger GetTrigger()
 {
     try
     {
         ITrigger trigger = null;
         string   cronExp = ConfigHelper.GetConfig("AutoJobCronExpression", "0 0/10 * * * ? *");
         if (QuartzHelper.ValidExpression(cronExp))
         {
             trigger = TriggerBuilder.Create().WithIdentity(JobName, "自动传8任务作业触发器")
                       .WithCronSchedule(cronExp).Build();
         }
         else
         {
             throw new Exception($"执行自动作业处理服务AutoAddJobService.GetTrigger(),配置AutoJobCronExpression的Cron表达式[{cronExp}]语法错误");
         }
         return(trigger);
     }
     catch (Exception ex)
     {
         throw new Exception($"自动作业处理服务AutoAddJobService.GetTrigger()异常,异常信息[{ex.Message}]");
     }
 }
Example #11
0
        public JsonResult Save(string data, string action)
        {
            try
            {
                var taskmodel = JsonHelper.ToObject <TaskModel>(data);

                var result = false;
                if (QuartzHelper.ValidExpression(taskmodel.CronExpressionString))
                {
                    result = MS.Common.TaskHelper.TaskActionHelper.AddTask(taskmodel, action);
                    return(Json(new { result = false, msg = "保存成功" }));
                }
                else
                {
                    return(Json(new { result = false, msg = "Cron表达式错误" }));
                }
            }
            catch (Exception ex)
            {
                return(Json(new { result = false, msg = ex.Message }));
            }
        }
Example #12
0
 public ActionResult RunJob(string serviceName, string jobName)
 {
     try {
         var info = QuartzHelper.GetServiceInfo(serviceName, true);
         if (info == null)
         {
             return(Json(new { code = 0, date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg = $"服务【{serviceName}】不存在!" }, JsonRequestBehavior.AllowGet));
         }
         var r = QuartzHelper.GetJob(info.Path, jobName);
         if (r == 0)
         {
             return(Json(new { code = 0, date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg = $"任务【{jobName}】不存在!" }, JsonRequestBehavior.AllowGet));
         }
         if (r == 2 && info.IsRun)
         {
             return(Json(new { code = 0, date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg = $"任务【{jobName}】将被执行或正在执行!" }, JsonRequestBehavior.AllowGet));
         }
         Process.Start(info.Path, jobName);
         return(Json(new { code = 1, date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg = $"任务【{jobName}】开始执行!" }, JsonRequestBehavior.AllowGet));
     } catch (Exception ex) {
         return(Json(new { code = 0, date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), msg = $"任务【{jobName}】执行出错:" + ex.Message }, JsonRequestBehavior.AllowGet));
     }
 }
Example #13
0
        /// <summary>
        /// 初始化任务信息
        /// </summary>
        /// <param name="name"></param>
        /// <param name="group"></param>
        public void InitJobInfo(string name, string group)
        {
            try
            {
                TaskEntity task = QuartzHelper.GetTask(name, group);

                this.txtTaskName.Value     = task.Name;
                this.txtTaskGroup.Value    = task.Group;
                this.txtAssemblyName.Value = task.AssemblyName;
                this.txtClassName.Value    = task.ClassName;
                this.txtTaskDecs.Value     = task.Description;
                this.txtBeginTime.Value    = task.BeginTime.ToString("yyyy-MM-dd HH:mm:ss");
                this.txtEndTime.Value      = task.EndTime == null ? "" : task.EndTime.ToString();
                if (task.Type == 0)
                {
                    this.radTypeSimple.Checked  = true;
                    this.txtRepeatCount.Value   = task.RepeatCount.ToString();
                    this.txtRepeatHours.Value   = task.RepeatInterval.Hours.ToString();
                    this.txtRepeatMinutes.Value = task.RepeatInterval.Minutes.ToString();
                    this.txtRepeatSeconds.Value = task.RepeatInterval.Seconds.ToString();
                    divCronPanel.Style.Add("display", "none");
                    divSimplePanel.Style.Add("display", "");
                }
                else
                {
                    this.radTypeCron.Checked = true;
                    this.txtCronExp.Value    = task.CronExpression.ToString();
                    divCronPanel.Style.Add("display", "");
                    divSimplePanel.Style.Add("display", "none");
                }
            }
            catch
            {
                OpenAlertModel("error", "获取任务信息错误");
            }
        }
Example #14
0
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                // 1. 获取Task 基本信息及 Task 配置的其他参数,任务启动时会读取配置文件节点的值传递过来
                TaskModel task = QuartzHelper.GetTaskDetail(context);
                // 2. 记录Task 运行状态数据库
                DbLogHelper.WriteRunInfo(task.TaskName + " 开始", task.TaskID.ToString(), "");
                // 3. 开始执行相关任务
                LogHelper.WriteLog(task.TaskName + ",当前系统时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                // 4. 记录Task 运行状态数据库
                DbLogHelper.WriteRunInfo(task.TaskName + " 结束", task.TaskID.ToString(), "成功执行");
            }
            catch (Exception ex)
            {
                JobExecutionException e2 = new JobExecutionException(ex);
                // 记录异常到数据库和 log 文件中。
                DbLogHelper.WriteErrorInfo(ex);
                LogHelper.WriteLog("测试任务异常", ex);

                //true  是立即重新执行任务
                e2.RefireImmediately = true;
            }
        }
Example #15
0
        public void ServiceRuntime()
        {
            var triggerDetails = TriggerRepository.GetCronTriggerDetails();
            var triggerDetailsSchedulerGroup = triggerDetails.GroupBy(a => new { a.SchedulerId, a.SchedulerName, a.SchedulerPriority, a.SchedulerThreadPoolSize }).ToDictionary(a => a.Key, a => a);

            //分组并创建调度器
            foreach (var schedulerGroupItem in triggerDetailsSchedulerGroup)
            {
                var scheduler = QuartzHelper.GetScheduler(schedulerGroupItem.Key.SchedulerName, schedulerGroupItem.Key.SchedulerThreadPoolSize, (int)schedulerGroupItem.Key.SchedulerPriority);
                foreach (var item in schedulerGroupItem.Value)
                {
                    //如果已经存在作业,需要先删除
                    var jobKey = new JobKey(item.JobCode, item.JobGroupName);
                    if (scheduler.CheckExists(jobKey))
                    {
                        scheduler.DeleteJob(jobKey);
                    }
                    var job = JobBuilder.Create <ExcuteJob>()
                              .WithIdentity(jobKey)
                              .Build();
                    //如果已经存在触发器,需要先删除
                    var triggerKey = new TriggerKey(item.TriggerCode);
                    if (scheduler.CheckExists(triggerKey))
                    {
                        scheduler.UnscheduleJob(triggerKey);
                    }
                    var trigger = TriggerBuilder.Create()
                                  .WithIdentity(triggerKey)
                                  .WithCronSchedule(item.CronExpression)
                                  .StartNow()
                                  .Build();
                    //调度作业
                    scheduler.ScheduleJob(job, trigger);
                }
            }
        }
Example #16
0
        public async Task <ActionResult> SyncJobs(int ID = 0)
        {
            string _group = "";

            try
            {
                // get all jobs from db
                IEnumerable <Job> jobs = db.Jobs.Include("JobParams");

                Job jobToSync = jobs.Where(o => o.ID == ID).SingleOrDefault();

                // remove missing jobs first
                IScheduler sched = await QuartzHelper.GetScheduler();

                IReadOnlyCollection <string> jobGroups = await sched.GetJobGroupNames();

                foreach (string group in jobGroups)
                {
                    var groupMatcher = Quartz.Impl.Matchers.GroupMatcher <JobKey> .GroupEquals(group);

                    var jobKeys = sched.GetJobKeys(groupMatcher);
                    foreach (var jobKey in jobKeys.Result)
                    {
                        // clear all jobs
                        if ((ID == 0) || (jobKey.Name.ToLower().Trim() == jobToSync.JobName.ToLower().Trim() && group.ToLower().Trim() == jobToSync.GroupName.ToLower().Trim()))
                        {
                            foreach (ITrigger triger in sched.GetTriggersOfJob(jobKey).Result)
                            {
                                // remove schedulers
                                // sched.UnscheduleJob(triger.Key);
                            }

                            await sched.DeleteJob(jobKey);                             // remove it from the service
                        }
                    }
                }

                // add all jobs to service
                foreach (Job job in jobs.Where(o => o.Enabled && (ID == 0 || o.ID == ID)))
                {
                    JobDataMap jdata = new JobDataMap();
                    foreach (JobParam param in job.JobParams)
                    {
                        jdata.Add(new KeyValuePair <string, object>(param.ParamKey, param.ParamValue));
                    }

                    IJobDetail sjob = JobBuilder
                                      .Create(Type.GetType(job.JobType))
                                      .WithIdentity(job.JobName, job.GroupName)
                                      .WithDescription(job.Details)
                                      .UsingJobData(jdata)
                                      .Build();

                    ITrigger strigger = TriggerBuilder
                                        .Create()
                                        .WithIdentity(job.TriggerName, job.TriggerGroup)
                                        .WithPriority(job.Priority)
                                        .StartNow()
                                        .WithCronSchedule(job.CronExpression)
                                        .Build();

                    if (ID > 0)
                    {
                        _group = job.GroupName;
                    }

                    await sched.ScheduleJob(sjob, strigger);
                }
            }
            catch (System.Net.Sockets.SocketException)
            {
                return(RedirectToAction("Index", "Home", new { group = _group }));
            }
            catch (Quartz.SchedulerException)
            {
                TempData["ErrorDetails"] = @"There was an error syncing jobs! Please consider using the <a href=""" + Url.Action("SyncJobs", new { id = 0 }) + @""">Sync All</a> feature if you recently changed the job name, group, trigger or trigger group. This is normal behavior in this case";
                return(RedirectToAction("Index", "Home"));
            }

            return(RedirectToAction("Index", "Home", new { group = _group }));
        }
Example #17
0
 static void Main(string[] args)
 {
     Log.Info("收到汇款单已退款通知", null, "收到汇款单已退款通知");
     QuartzHelper.ExecuteAtTime(ForeignExchange, "*/55 * * * * ?");
 }
Example #18
0
        public TaskModule() : base("Task")
        {
            //任务列表
            Get["/Grid"] = r =>
            {
                return(View["Grid"]);
            };
            //任务编辑界面
            Get["/Edit"] = r =>
            {
                return(View["Edit"]);
            };

            #region "取数接口API"

            //立即运行一次任务
            Get["/Run/{Id}"] = r =>
            {
                //取出单条记录数据
                string             TaskId = r.Id;
                ApiResult <string> result = new ApiResult <string>();
                try
                {
                    TaskHelper.RunById(TaskId);
                }
                catch (Exception ex)
                {
                    result.HasError = true;
                    result.Message  = ex.Message;
                }
                return(Response.AsJson(result));
            };

            Get["/GetById/{Id}"] = r =>
            {
                ApiResult <TaskUtil> result = new ApiResult <TaskUtil>();
                try
                {
                    //取出单条记录数据
                    string TaskId = r.Id;
                    result.Result = TaskHelper.GetById(TaskId);
                }
                catch (Exception ex)
                {
                    result.HasError = true;
                    result.Message  = ex.Message;
                }
                return(Response.AsJson(result));
            };

            //列表查询接口
            Post["/PostQuery"] = r =>
            {
                QueryCondition condition = this.Bind <QueryCondition>();
                return(Response.AsJson(TaskHelper.Query(condition)));
            };

            //重新加载任务接口
            Post["/Reload"] = r =>
            {
                ApiResult <string> result = new ApiResult <string>();
                try
                {
                    List <string> listTaskId = this.Bind <List <string> >();
                    foreach (string TaskId in listTaskId)
                    {
                        var taskUtil = TaskHelper.GetById(TaskId);
                        QuartzHelper.ScheduleJob(taskUtil, true);
                    }
                }
                catch (Exception ex)
                {
                    result.HasError = true;
                    result.Message  = ex.Message;
                }
                return(Response.AsJson(result));
            };

            //保存数据
            Post["/"] = r =>
            {
                TaskUtil TaskUtil = this.Bind <TaskUtil>();
                return(Response.AsJson(TaskHelper.SaveTask(TaskUtil)));
            };
            //更新数据
            Put["/"] = r =>
            {
                TaskUtil TaskUtil = this.Bind <TaskUtil>();
                return(Response.AsJson(TaskHelper.SaveTask(TaskUtil)));
            };
            //删除任务接口
            Delete["/{Id}"] = r =>
            {
                ApiResult <string> result = new ApiResult <string>();
                try
                {
                    string TaskId = r.Id;
                    TaskHelper.DeleteById(TaskId);
                }
                catch (Exception ex)
                {
                    result.HasError = true;
                    result.Message  = ex.Message;
                }
                return(Response.AsJson(result));
            };

            //更新任务运行状态
            Put["/{Id}/{Status:int}"] = r =>
            {
                ApiResult <string> result = new ApiResult <string>();
                try
                {
                    TaskStatus Status = Enum.ToObject(typeof(TaskStatus), r.Status);
                    string     TaskId = r.Id;
                    TaskHelper.UpdateTaskStatus(TaskId, Status);
                }
                catch (Exception ex)
                {
                    result.HasError = true;
                    result.Message  = ex.Message;
                }
                return(Response.AsJson(result));
            };
            #endregion
        }
Example #19
0
 public string GetCronExpressionDetails(string cron)
 {
     return(QuartzHelper.GetCronExpressionDescription(cron));
 }
Example #20
0
        static void Main(string[] args)
        {
            AdminRun.Run();

            if (!SetConsoleCtrlHandler(cancelHandler, true))
            {
                Console.WriteLine("程序监听系统按键异常");
            }
            try
            {
                //1.MEF初始化
                MefConfig.Init();

                //2.数据库初始化连接
                ConfigInit.InitConfig();

                //3.系统参数配置初始化
                ConfigManager configManager = MefConfig.TryResolve <ConfigManager>();
                configManager.Init();

                Console.Title         = SystemConfig.ProgramName;
                Console.CursorVisible = false; //隐藏光标

                //4.任务启动
                QuartzHelper.InitScheduler();
                QuartzHelper.StartScheduler();

                //5.加载SQL信息到缓存中
                XmlCommandManager.LoadCommnads(SysConfig.XmlCommandFolder);
                //开发时监听资源文件变化,用于实时更新
                DevelperHelper.WatcherResourceChange();

                //测试dapper orm框架
                //DapperDemoService.Test();

                //启动站点
                using (NancyHost host = Startup.Start(SystemConfig.WebPort))
                {
                    //调用系统默认的浏览器
                    string url = string.Format("http://127.0.0.1:{0}", SystemConfig.WebPort);
                    Process.Start(url);
                    Console.WriteLine("系统已启动,当前监听站点地址:{0}", url);
                    try
                    {
                        //4.消息队列启动
                        RabbitMQClient.InitClient();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                    }
                    //5.系统命令初始化
                    CommandHelp.Init();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            Console.Read();
        }
Example #21
0
 public string GetCronExpressionString()
 {
     return(QuartzHelper.GenerateCronExpression(_cronExpressionEntity));
 }
Example #22
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="identity"></param>
 public QuartzCommand(UserIdentity identity) : base(identity)
 {
     quartz = new QuartzHelper();
 }
 /// <summary>
 /// 获取Cron表达式串
 /// </summary>
 /// <returns></returns>
 public string GetCronExpressionString()
 {
     return(QuartzHelper.GenerateCronExpression(BuildCronExpression()));
 }
Example #24
0
 /// <summary>
 /// Resumes all activity in server.
 /// </summary>
 public void Resume()
 {
     QuartzHelper.ResumeAll();
 }
Example #25
0
        public void Stop()
        {
            QuartzHelper.StopSchedule();

            System.Environment.Exit(0);
        }
Example #26
0
 /// <summary>
 /// Pauses all activity in scheduler.
 /// </summary>
 public virtual void Pause()
 {
     QuartzHelper.PauseAll();
 }
Example #27
0
        protected override void OnStart(string[] args)
        {
            AppDomain.MonitoringIsEnabled = true;

            AdminRun.Run();

            DebuggableAttribute att = System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttribute <DebuggableAttribute>();

            if (att.IsJITTrackingEnabled)
            {
                //Debug模式才让线程停止10s,方便附加到进程调试
                Thread.Sleep(10000);
            }
            if (!SetConsoleCtrlHandler(cancelHandler, true))
            {
                LogHelper.WriteLog("程序监听系统按键异常");
            }
            try
            {
                //1.MEF初始化
                MefConfig.Init();
                LogHelper.WriteLog("MEF初始化");

                //2.数据库初始化连接
                ConfigInit.InitConfig();
                LogHelper.WriteLog("数据库初始化连接");

                //3.系统参数配置初始化
                ConfigManager configManager = MefConfig.TryResolve <ConfigManager>();
                configManager.Init();
                LogHelper.WriteLog("系统参数配置初始化");

                //4.任务启动
                QuartzHelper.InitScheduler();
                QuartzHelper.StartScheduler();
                LogHelper.WriteLog("任务启动");

                //5.加载SQL信息到缓存中
                XmlCommandManager.LoadCommnads(SysConfig.XmlCommandFolder);
                LogHelper.WriteLog("加载SQL信息到缓存中");

                //测试dapper orm框架
                //DapperDemoService.Test();

                #region 控制台用死循环监听

                ////启动站点
                //using (NancyHost host = Startup.Start(SystemConfig.WebPort))
                //{
                //    //调用系统默认的浏览器
                //    string url = string.Format("http://127.0.0.1:{0}", 9059);
                //    Process.Start(url);
                //    LogHelper.WriteLog( string.Format("系统已启动,当前监听站点地址:{0}", url));

                //    //4.消息队列启动
                //    RabbitMQClient.InitClient();

                //    LogHelper.WriteLog("消息队列启动");

                //    ////5.系统命令初始化

                //    CommandHelp.Init();
                //    LogHelper.WriteLog("系统命令初始化");
                //}

                #endregion

                ///Window服务用线程池
                ThreadPool.QueueUserWorkItem((o) =>
                {
                    //启动站点
                    string url = string.Format("http://127.0.0.1:{0}", SysConfig.WebPort);
                    Startup.Start(SysConfig.WebPort);
                    LogHelper.WriteLog(string.Format("系统已启动,当前监听站点地址:{0}", url));

                    //4.消息队列启动
                    //RabbitMQClient.InitClient();
                    LogHelper.WriteLog("消息队列启动");
                });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex.Message);
            }
        }
 protected override void OnStop()
 {
     QuartzHelper.StopSchedule();
     System.Environment.Exit(0);
 }
Example #29
0
        public ToolModule() : base("Tool")
        {
            //数据库表
            Get["/TableList"] = r =>
            {
                ViewBag.TableList = JsonConvert.SerializeObject(TableListService.GetAllTable());
                return(View["TableList"]);
            };

            //CronExpress表达式生成器FGZDZDZDZDZDZDZ
            Get["/CronExpress"] = r =>
            {
                return(View["CronExpress"]);
            };

            //命令行执行工具
            Get["/CommandLine"] = r =>
            {
                return(View["CommandLine"]);
            };

            //系统日志
            Get["/SysLog"] = r =>
            {
                return(View["SysLog"]);
            };

            //异常信息
            Get["/ExceptionLog"] = r =>
            {
                return(View["ExceptionLog", LogHelper.GetExceptionMsg()]);
            };
            #region "接口"

            //生成实体代码
            Post["/QuickCode"] = r =>
            {
                string strTableList = Request.Form["TableList"];
                if (string.IsNullOrEmpty(strTableList))
                {
                    return(null);
                }
                string FileName = string.Format("EntityCode-{0}.zip", DateTime.Now.ToString("yyyyMMddHHmmss"));
                var    res      = new Response()
                {
                    Contents    = stream => { EntityCodeHelper.QuickCode(TableListService.GetTableInfo(strTableList.Split(',')), stream); },
                    ContentType = MimeHelper.GetMineType(FileName),
                    StatusCode  = HttpStatusCode.OK,
                    Headers     = new Dictionary <string, string> {
                        { "Content-Disposition", string.Format("attachment;filename={0}", System.Web.HttpUtility.UrlPathEncode(FileName)) }
                    }
                };
                return(res);
            };

            //计算表达式最近五次运行时间
            Get["/CalcRunTime"] = r =>
            {
                string CronExpressionString = Request.Query["CronExpression"];
                if (string.IsNullOrEmpty(CronExpressionString))
                {
                    return("[]");
                }
                else
                {
                    JsonSerializerSettings setting = new JsonSerializerSettings();
                    setting.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                    return(JsonConvert.SerializeObject(QuartzHelper.GetTaskeFireTime(CronExpressionString, 5), setting));
                }
            };

            //获取命令行返回结果
            Post["/Cmd"] = r =>
            {
                string strCmd = Request.Form["cmd"];
                return(CommandHelp.ExcuteCommad(strCmd));
            };

            //删除异常消息
            Get["/DeleteException"] = r =>
            {
                string type  = Request.Query["Type"];
                string Index = Request.Query["Index"];
                if ("Delete".Equals(type, StringComparison.CurrentCultureIgnoreCase))
                {
                    long key;
                    if (long.TryParse(Index, out key))
                    {
                        LogHelper.RemoveExceptionMsg(key);
                    }
                }
                else if ("Clear".Equals(type, StringComparison.CurrentCultureIgnoreCase))
                {
                    LogHelper.ClearExceptionMsg();
                }
                return(string.Empty);
            };
            #endregion
        }
Example #30
0
        public void Execute(IJobExecutionContext context)
        {
            try
            {
                TaskLog.ConfigLogInfo.WriteLogE("Job修改任务开始,当前系统时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                ///获取所有执行中的任务
                List <TaskUtil> listTask = TaskHelper.ReadConfig().Where(e => e.IsExcute).ToList <TaskUtil>();
                //开始对比当前配置文件和上一次配置文件之间的改变

                //1.修改的任务
                var UpdateJobList = (from p in listTask
                                     from q in TaskHelper.CurrentTaskList
                                     where p.TaskID == q.TaskID && (p.TaskParam != q.TaskParam || p.Assembly != q.Assembly || p.Class != q.Class ||
                                                                    p.CronExpressionString != q.CronExpressionString
                                                                    )
                                     select new { NewTaskUtil = p, OriginTaskUtil = q }).ToList();
                foreach (var item in UpdateJobList)
                {
                    try
                    {
                        QuartzHelper.ScheduleJob(item.NewTaskUtil);
                        //修改原有的任务
                        int index = TaskHelper.CurrentTaskList.IndexOf(item.OriginTaskUtil);
                        TaskHelper.CurrentTaskList[index] = item.NewTaskUtil;
                    }
                    catch (Exception e)
                    {
                        TaskLog.ConfigLogError.WriteLogE(string.Format("任务“{0}”配置信息更新失败!", item.NewTaskUtil.TaskName), e);
                    }
                }

                //2.新增的任务(TaskID在原集合不存在)
                var AddJobList = (from p in listTask
                                  where !(from q in TaskHelper.CurrentTaskList select q.TaskID).Contains(p.TaskID)
                                  select p).ToList();

                foreach (var taskUtil in AddJobList)
                {
                    try
                    {
                        QuartzHelper.ScheduleJob(taskUtil);
                        //添加新增的任务
                        TaskHelper.CurrentTaskList.Add(taskUtil);
                    }
                    catch (Exception e)
                    {
                        TaskLog.ConfigLogError.WriteLogE(string.Format("任务“{0}”新增失败!", taskUtil.TaskName), e);
                    }
                }

                //3.删除的任务
                var DeleteJobList = (from p in TaskHelper.CurrentTaskList
                                     where !(from q in listTask select q.TaskID).Contains(p.TaskID)
                                     select p).ToList();
                foreach (var taskUtil in DeleteJobList)
                {
                    try
                    {
                        QuartzHelper.DeleteJob(taskUtil.TaskID);
                        //添加新增的任务
                        TaskHelper.CurrentTaskList.Remove(taskUtil);
                    }
                    catch (Exception e)
                    {
                        TaskLog.ConfigLogError.WriteLogE(string.Format("任务“{0}”删除失败!", taskUtil.TaskName), e);
                    }
                }
                if (UpdateJobList.Count > 0 || AddJobList.Count > 0 || DeleteJobList.Count > 0)
                {
                    TaskLog.ConfigLogInfo.WriteLogE("Job修改任务执行完成后,系统当前的所有任务信息:" + JsonConvert.SerializeObject(TaskHelper.CurrentTaskList));
                }
                else
                {
                    TaskLog.ConfigLogInfo.WriteLogE("当前没有修改的任务");
                }
            }
            catch (Exception ex)
            {
                JobExecutionException e2 = new JobExecutionException(ex);
                TaskLog.ConfigLogError.WriteLogE("Job修改任务异常", ex);
                //1.立即重新执行任务
                e2.RefireImmediately = true;
            }
        }