Example #1
0
        /// <summary>运行任务</summary>
        protected bool ProcessTask(Job task, DateTime dt)
        {
            // 当它不存在
            if (!task.Enable)
            {
                return(true);
            }

            // 是否处于运行时间内
            if (!task.Schedule.InTime(dt))
            {
                return(false);
            }

            // 成功状态,且未到下次运行时间
            if (task.Status == JobStatus.Success && !NeedToRunAgain(task.LastRunDt, task.Success, dt))
            {
                return(true);
            }

            // 失败状态,但又要开始一个周期了
            if (task.Status == JobStatus.Failure && NeedToRunAgain(task.LastRunDt, task.Success, dt))
            {
                task.Failure.TryTimes = 0;
                task.Status           = JobStatus.Waiting;
            }

            // 处于等待状态;或与上次运行成功的间隔时间足够了;或上次运行失败的间隔时间足够了(且失败次数未饱和);
            if (
                (task.Status == JobStatus.Waiting && NeedToRunAgain(task.LastRunDt, task.Success, dt)) ||
                (task.Status == JobStatus.Success && NeedToRunAgain(task.LastRunDt, task.Success, dt)) ||
                (task.Status == JobStatus.Failure && NeedToRunAgain(task.LastRunDt, task.Failure, dt) && task.Failure.TryTimes < task.Failure.MaxTimes)
                )
            {
                TaskRunning?.Invoke(task, "");

                // 先运行依赖任务
                if (task.Dependency != null && task.Dependency.Count > 0)
                {
                    foreach (var t in task.Dependency)
                    {
                        if (!ProcessTask(t, dt))
                        {
                            return(false);
                        }
                    }
                }

                // 再运行本任务
                task.LastRunDt = dt;
                task.Status    = JobStatus.Waiting;
                try
                {
                    var runner = task.JobRunner;

                    // TODO: 改为异步任务或者线程
                    if (runner.Run(dt, task.Data))
                    {
                        task.Status           = JobStatus.Success;
                        task.Failure.TryTimes = 0;
                        TaskSuccess?.Invoke(task, "");
                        return(true);
                    }
                    else
                    {
                        task.Status = JobStatus.Failure;
                        task.Failure.TryTimes++;
                        TaskFailure?.Invoke(task, "");
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    task.Status = JobStatus.Failure;
                    task.Failure.TryTimes++;
                    TaskFailure?.Invoke(task, ex.Message);
                }
            }

            return(false);
        }
Example #2
0
 public async void Resolve()
 {
     taskSuccess?.Invoke();
 }