Esempio n. 1
0
File: IJob.cs Progetto: xiawei666/X
 /// <param name="context"></param>
 public abstract void Execute(JobContext context);
Esempio n. 2
0
        /// <summary>线程包装</summary>
        /// <param name="data">线程序号</param>
        private void WorkWaper(Object data)
        {
            var index = (Int32)data;
            var ev    = Event = new AutoResetEvent(false);

            Active = true;
            var set = Setting.Current;

            var ctx = new JobContext();

            ctx["Worker"] = this;
            while (true)
            {
                var isContinute = false;
                LastActive = TimerX.Now;

                var sw = Stopwatch.StartNew();
                try
                {
                    if (Callback != null)
                    {
                        isContinute = Callback(Index);
                    }
                    else if (Job != null)
                    {
                        Job.Execute(ctx);
                    }
                }
                catch (ThreadAbortException)
                {
                    Active = false;
                    WriteLine("线程[{0}]被取消!", index);
                    break;
                }
                catch (ThreadInterruptedException)
                {
                    Active = false;
                    WriteLine("线程[{0}]中断错误!", index);
                    break;
                }
                catch (Exception ex)
                {
                    // 确保拦截了所有的异常,保证服务稳定运行
                    WriteLine(ex?.GetTrue() + "");
                }
                sw.Stop();
                LastActive = TimerX.Now;

                if (set.Debug && set.WaitForExit > 0 && sw.ElapsedMilliseconds > set.WaitForExit)
                {
                    WriteLine("工作任务耗时较长 {0:n0}ms > {1:n0}ms,需要调整业务缩小耗时,以确保任务得到可靠保护", sw.ElapsedMilliseconds, set.WaitForExit);
                }

                // 检查服务是否正在重启
                if (!Active)
                {
                    WriteLine("停止服务,线程[{0}]退出", index);
                    break;
                }

                var time = Interval;

                if (!isContinute)
                {
                    ev.WaitOne(time * 1000);
                }

                if (!Active)
                {
                    WriteLine("停止服务,线程[{0}]退出", index);
                    break;
                }
            }

            ev.Dispose();
            Event = null;
        }