Пример #1
0
        /// <summary>
        /// 重置应用
        /// 清空作业、作业项、统计、错误,开始时间设为本月一号
        /// </summary>
        /// <returns></returns>
        public ActionResult ResetApp()
        {
            var ids = GetRequest("keys").SplitAsInt();

            if (!ids.Any())
            {
                return(JsonRefresh("未选中项!"));
            }

            var now = DateTime.Now;

            foreach (var appid in ids)
            {
                // 清空作业
                var jobs = Job.FindAllByAppID2(appid);
                foreach (var job in jobs)
                {
                    job.Start = new DateTime(now.Year, now.Month, 1);
                    job.ResetOther();
                }

                // 清空日志
                var jobItems = JobTask.FindAllByAppID(appid);
                foreach (var jobItem in jobItems)
                {
                    jobItem.Delete();
                }

                // 清空错误
                JobError.DeleteByAppId(appid);
            }

            return(JsonRefresh("操作完毕!"));
        }
Пример #2
0
        private JobError SetJobError(Job job, JobTask task)
        {
            var err = new JobError
            {
                AppID  = job.AppID,
                JobID  = job.ID,
                TaskID = task.ID,
                Start  = task.Start,
                End    = task.End,
                Data   = task.Data,

                Server    = task.Server,
                ProcessID = task.ProcessID,
                Client    = task.Client,

                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
            };

            var msg = task.Message;

            if (!msg.IsNullOrEmpty() && msg.Contains("Exception:"))
            {
                msg = msg.Substring("Exception:").Trim();
            }
            err.Message = msg;

            err.Insert();

            return(err);
        }
Пример #3
0
 public static JobExecutionResult <T> Failed <T>(JobError error) where T : class
 {
     if (error is null)
     {
         throw new ArgumentNullException(nameof(error));
     }
     return(new JobExecutionResult <T>
     {
         IsFinished = false,
         Error = error
     });
 }
Пример #4
0
        private void CallJobCompleted(bool success = true, JobError errorType = JobError.None)
        {
            Completed = true;
            if (success)
            {
                JobState = JobState.Succeeded;
            }
            ErrorType = errorType;

            if (OnJobCompleted != null)
            {
                OnJobCompleted(this, new JobCompletedEventArgs(this));
            }
        }
Пример #5
0
 public static ErrorDto ToDto(this JobError error)
 {
     if (error == null)
     {
         return(new ErrorDto());
     }
     return(new ErrorDto()
     {
         Date = error.Date,
         Message = error.Message,
         StackTrace = error.StackTrace
     }
            );
 }
Пример #6
0
        public static JobFailed FromError(JobError error)
        {
            string message        = error.Message;
            var    innerException = GenerateInnerException(error);

            if (innerException is null)
            {
                return(new JobFailed(message, error.Data));
            }
            else
            {
                return(new JobFailed(message, innerException));
            }
        }
        public override string ToString()
        {
            string s = base.ToString() + " ";

            s += "success=" + Successful.ToString();
            if (JobError != null)
            {
                s += "\n" + JobError.ToString() + "\n" + JobError.StackTrace;
            }
            if (Stats != null)
            {
                s += "\n" + Stats.ToString();
            }
            return(s);
        }
            private void RunJob(object rawJob)
            {
                JobInfo jobInfo = (JobInfo)rawJob;

                try
                {
                    RunJobSynchronously(jobInfo);
                }
                catch (System.Exception ex)
                {
                    JobError jobError = new JobError(jobInfo, ex);
                    lock (errorQueue)
                    {
                        errorQueue.Enqueue(jobError);
                    }
                }
            }
Пример #9
0
        private JobError SetJobError(IJob job, JobLog ji, IDictionary <String, Object> ps)
        {
            var err = new JobError
            {
                AppID      = job.AppID,
                JobID      = job.ID,
                Start      = ji.Start,
                End        = ji.End,
                Row        = ji.Row,
                Step       = ji.Step,
                BatchSize  = ji.BatchSize,
                CreateTime = DateTime.Now,
                UpdateTime = DateTime.Now,
                Server     = ji.Server,
                ProcessID  = ji.ProcessID,
                ThreadID   = ji.ThreadID,
                Client     = ji.Client,
            };

            err.Key = ji.Key;

            err.Data = ps["Data"] + "";

            var code = ps["ErrorCode"] + "";

            if (code != nameof(Exception))
            {
                code = code.TrimEnd(nameof(Exception));
            }
            err.ErrorCode = code;

            var msg = ji.Message;

            if (!msg.IsNullOrEmpty() && msg.Contains("Exception:"))
            {
                msg = msg.Substring("Exception:").Trim();
            }
            err.Message = msg;

            err.Insert();

            return(err);
        }
Пример #10
0
 private async Task OnError(ErrorArgs args, Delivery delivery)
 {
     _logger.LogWarning(args.Exception, args.Message);
     if (args.Job is not null)
     {
         var      job = args.Job;
         JobError jobError;
         if (args.Exception is null)
         {
             jobError = JobError.FromMessage(args.Message);
         }
         else
         {
             jobError = JobError.FromException(args.Exception);
         }
         job.Error(jobError);
         await _jobRepository.UpdateAsync(job, CancellationToken.None);
     }
 }
Пример #11
0
        private static Exception?GenerateInnerException(JobError error)
        {
            var exceptionType = Type.GetType(error.Type, false, true);

            if (exceptionType is null)
            {
                return(null);
            }
            try
            {
                var exception = Activator.CreateInstance(exceptionType, error.Message) as Exception;
                exception?.SetStackTrace(error.StackTrace);
                exception?.AddData(error.Data);
                return(exception);
            }
            catch
            {
                return(null);
            }
        }
Пример #12
0
        public ActionResult ClearErrorItem()
        {
            var ids = Request["keys"].SplitAsInt(",");

            Parallel.ForEach(ids, k =>
            {
                var dt = JobError.FindAllByJobId(k);
                if (dt.Count < 20000)
                {
                    dt.Delete(true);
                }

                var dtt = JobX.FindByID(k);
                if (dtt != null)
                {
                    dtt.Error = 0;
                    dtt.Save();
                }
            });

            return(JsonRefresh("操作成功!"));
        }
Пример #13
0
 /// <summary>
 /// Raises the JobError event.
 /// </summary>
 /// <param name="e"></param>
 protected virtual void OnJobError(JobErrorEventArgs e)
 {
     JobError?.Invoke(this, e);
 }
Пример #14
0
 protected virtual void OnJobError(ServiceJob job, Exception ex)
 {
     JobError?.Invoke(this, new JobException(job, ex));
 }
Пример #15
0
        /// <summary>
        /// Scheduler在JobDetail被执行之后调用这个方法
        /// </summary>
        /// <param name="context"></param>
        /// <param name="jobException"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task JobWasExecuted(IJobExecutionContext context, JobExecutionException jobException, CancellationToken cancellationToken = default)
        {
            try
            {
                lock (_lock)
                {
                    var trigger   = (CronTriggerImpl)((JobExecutionContextImpl)context).Trigger;
                    var result    = context.Scheduler.Context.Get(trigger.FullName + "_Result");    /*返回结果*/
                    var exception = context.Scheduler.Context.Get(trigger.FullName + "_Exception"); /*异常信息*/
                    var time      = context.Scheduler.Context.Get(trigger.FullName + "_Time");      /* 耗时*/

                    var jobinfo_repository = IocEx.Instance.GetService <IJobInfoRepository>();

                    var job = jobinfo_repository.Get(x => x.JobName.Equals(trigger.Name) && x.JobGroup.Equals(trigger.JobGroup) && x.IsDelete == 0);

                    if (job == null)
                    {
                        job = new JobInfo
                        {
                            Id         = Guid.NewGuid().ToString(),
                            JobName    = trigger.JobName,
                            JobGroup   = trigger.JobGroup,
                            JobValue   = context.JobDetail.JobDataMap.ToJson(),
                            IsDelete   = 0,
                            JobCount   = 1,
                            JobClass   = context.JobDetail.JobType.FullName,
                            JobStatus  = (int)TriggerState.Normal,
                            JobResult  = result.ToJson(),
                            JobCron    = trigger.CronExpressionString,
                            CreateTime = DateTime.Now,
                            JobRunTime = time != null?Convert.ToInt32(time) : 0,
                                             JobStartTime = trigger.StartTimeUtc.LocalDateTime,
                                             JobNextTime  = trigger.GetNextFireTimeUtc().GetValueOrDefault().LocalDateTime
                        };
                        jobinfo_repository.Add(job, true);
                    }
                    else
                    {
                        job.JobStartTime = trigger.StartTimeUtc.LocalDateTime;
                        job.JobValue     = context.JobDetail.JobDataMap.ToJson();
                        job.JobCron      = trigger.CronExpressionString;
                        job.JobCount    += 1;
                        job.JobRunTime   = time != null?Convert.ToInt32(time) : 0;

                        job.JobNextTime = trigger.GetNextFireTimeUtc().GetValueOrDefault().LocalDateTime;
                        job.UpdateTime  = DateTime.Now;
                        job.JobResult   = result.ToJson();
                        jobinfo_repository.Update(job, true);
                    }

                    //记录错误
                    if (exception != null)
                    {
                        var joberror_repository = IocEx.Instance.GetService <IJobErrorRepository>();
                        var error = new JobError
                        {
                            Id         = Guid.NewGuid().ToString(),
                            JobId      = job.Id,
                            JobCount   = job.JobCount,
                            IsDelete   = 0,
                            CreateTime = DateTime.Now,
                            Message    = exception.ToJson()
                        };

                        joberror_repository.Add(error, true);
                    }

                    ApplicationLog.CreateLogger <JobListener>().LogInformation($"任务监听:{job.ToJson()}");
                    return(Task.CompletedTask);
                }
            }
            catch (Exception ex)
            {
                ApplicationLog.CreateLogger <JobListener>().LogError(new EventId(ex.HResult), ex, "---JobWasExecuted Exception---");
                return(Task.CompletedTask);
            }
        }
Пример #16
0
        private async Task OnNewJob(Job job, Delivery delivery)
        {
            bool updateStatus = true;
            var  cancel       = new CancellationTokenSource(
                _workerConfiguration.MaximumAllowedExecutionTime)
                                .Token;

            try
            {
                if (job.Input is null)
                {
                    throw new ArgumentNullException(nameof(job.Input));
                }
                using var scope = _scopeFactory.CreateScope(job);
                var worker = scope.GetWorker <TWorker>();
                var input  = _inputSerializer.Deserialize(job.Input);
                job.Start(worker.EstimateExecutionTime(input));
                await _jobRepository.UpdateAsync(job, cancel);

                var result = await worker.ExecuteAsync(input, cancel);

                if (result.IsCancelled)
                {
                    job.Cancel();
                    delivery.Acknowledge = true;
                    return;
                }
                if (result.IsFinished)
                {
                    if (result.Output is null)
                    {
                        throw new InvalidOperationException("Job finished without output");
                    }
                    string output = _outputSerializer.Serialize(result.Output);
                    job.Finish(output);
                    delivery.Acknowledge = true;
                    return;
                }
                if (result.IsError)
                {
                    if (delivery.SupportsRepeat)
                    {
                        updateStatus = false;
                    }
                    else
                    {
                        delivery.Acknowledge = true;
                        if (result.Error is not null)
                        {
                            job.Error(result.Error);
                        }
                        else
                        {
                            var genericError = JobError.FromMessage("Job execution failed");
                            job.Error(genericError);
                        }
                    }
                }
            }
            catch (OperationCanceledException e)
            {
                if (delivery.SupportsRepeat)
                {
                    updateStatus = false;
                }
                else
                {
                    delivery.Acknowledge = true;
                    job.Error(e);
                }
            }
            catch (Exception e)
            {
                delivery.Acknowledge = true;
                job.Error(e);
            }
            finally
            {
                if (updateStatus)
                {
                    await _jobRepository.UpdateAsync(job, CancellationToken.None);
                }
            }
        }