/// <summary> /// 执行计划任务。 /// </summary> protected override void ScheduleCallback() { while (true) { while (ScheduledTasks.TaskExecuting) { Thread.Sleep(1000); } try { ScheduledTasks.TaskExecuting = true; base.ExecuteTask(); ScheduledTaskLog.WriteLog(Config); } catch (Exception exception) { ExceptionHandler.HandleException(exception); } finally { ScheduledTasks.TaskExecuting = false; } Thread.Sleep((int)(Config.ThreadSleepSecond * 1000)); } }
/// <summary> /// 处理单个定时任务 /// </summary> /// <param name="executor">定时任务执行器</param> protected virtual void HandleTask(IScheduledTask executor) { // 执行任务并捕捉错误 bool executed = false; bool success = false; string error = null; try { executed = HandleTaskInner(executor); success = true; } catch (Exception e) { error = e.ToString(); } if (!executed && error == null) { return; } // 记录日志 using (UnitOfWork.Scope()) { var logRepository = ZKWeb.Application.Ioc.Resolve <IRepository <ScheduledTaskLog, Guid> >(); var log = new ScheduledTaskLog() { Task = Get(executor.Key), CreateTime = DateTime.UtcNow, Success = success, Error = error }; logRepository.Save(ref log); } }
/// <summary> /// 执行计划任务。 /// </summary> protected override void ScheduleCallback() { while (true) { if (this.lastExecuteTime.AddDays(1.0) < DateTime.Now) { while (ScheduledTasks.TaskExecuting) { Thread.Sleep(1000); } try { ScheduledTasks.TaskExecuting = true; base.ExecuteTask(); this.lastExecuteTime = DateTime.Today; ScheduledTaskLog.WriteLog(base.Config); } catch (Exception exception) { ExceptionHandler.HandleException(exception); } finally { ScheduledTasks.TaskExecuting = false; } } Thread.Sleep((int)(base.Config.ThreadSleepSecond * 1000)); } }
public void CreateScheduleTaskLog(ScheduledTask task) { var log = new ScheduledTaskLog(); log.RunDate = DateTime.UtcNow; log.Successful = true; log.ScheduledTaskId = task.ScheduledTaskId; _scheduledTaskLogRepository.SaveOrUpdate(log); }
public async Task <ScheduledTaskLog> CreateScheduleTaskLogAsync(ScheduledTask task, CancellationToken cancellationToken = default(CancellationToken)) { var log = new ScheduledTaskLog(); log.RunDate = DateTime.UtcNow; log.Successful = true; log.ScheduledTaskId = task.ScheduledTaskId; return(await _scheduledTaskLogRepository.SaveOrUpdateAsync(log, cancellationToken)); }
public ScheduledTaskLog WriteTaskLog(ScheduledTask task, string message, LogSeverity severity = LogSeverity.Normal) { ScheduledTaskLog log = new ScheduledTaskLog { ScheduledTask = task, Severity = (int)severity, LogDate = DateTime.Now, Message = message }; db.InsertOrUpdateScheduledTaskLog(log); return(log); }
/// <summary> /// /// </summary> /// <param name="context"></param> public void Execute(IJobExecutionContext context) { try { _task = (ScheduledTask)context.MergedJobDataMap["ScheduledTask"]; DateTime planingTime = context.ScheduledFireTimeUtc.HasValue ? context.ScheduledFireTimeUtc.Value.LocalDateTime : DateTime.Now; planingTime = new DateTime(planingTime.Ticks - (planingTime.Ticks % TimeSpan.TicksPerMinute), planingTime.Kind); if (_task.OnlyWorkingDays) { if (HolidayCalculator.Instance.IsHoliday(planingTime, _task.RunAtHalfPublicHoliday)) { return; } } _action = Toolkit.Instance.CreateInstance <IPxTaskAction>(_task.Action); using (PeakDbContext dbContext = new PeakDbContext()) { if (dbContext.ScheduledTaskLogs.FirstOrDefault(x => x.ScheduledTaskId == _task.Id && x.ScheduledTime == planingTime) != null) { return; } ScheduledTaskLog taskLog = new ScheduledTaskLog() { ScheduledTaskId = _task.Id, State = Dal.Enums.ScheduleState.Running, ScheduledTime = planingTime, StartTime = DateTime.Now }; dbContext.ScheduledTaskLogs.Add(taskLog); dbContext.SaveChanges(); bool succeed = executeAction(planingTime, 0); taskLog.EndTime = DateTime.Now; if (succeed) { taskLog.State = Dal.Enums.ScheduleState.Succeed; } else { taskLog.State = Dal.Enums.ScheduleState.Failed; if (_lastError != null) { taskLog.ErrorMessage = _lastError.Message; taskLog.ErrorDetail = _lastError.ToString(); _lastError = null; } } dbContext.SaveChanges(); } } catch (Exception ex) { PxErrorLogger.Log(ex); } }
public async Task SaveScheduledTaskLogAsync(ScheduledTaskLog scheduledTaskLog) { if (scheduledTaskLog.ScheduledTaskLogId == Guid.Empty) { _context.Add(scheduledTaskLog); } else { if (ScheduledTaskLogExists(scheduledTaskLog.ScheduledTaskLogId)) { _context.Update(scheduledTaskLog); } } await _context.SaveChangesAsync(); }
// == EVENT(S) // ====================================================================== /// <summary> /// Event called before the start of the task execution. /// </summary> protected virtual void onStart() { this._message = new JObject(); // == CREATES THE SCOPE & DATABASE CONTEXT this._scope = this._scopeFactory.CreateScope(); this._databaseContext = this._scope.ServiceProvider.GetRequiredService <DatabaseContext>(); // == CREATES THE ENTRY OF THIS SCAN ON DATABASE var currentTime = DateTime.Now; this._databaseTransaction = this._databaseContext.Database.BeginTransaction(); // SCHEDULED_TASK_LOG if (!this._newTentative) { this._taskLog = new ScheduledTaskLog(); this._taskLog.StartTime = currentTime; this._taskLog.ScheduledTaskNavigation = this._scheduledTask; this._databaseContext.Entry(this._taskLog.ScheduledTaskNavigation).State = EntityState.Unchanged; this._taskLog.ScheduledTask = this._scheduledTask.Id; this._databaseContext.ScheduledTaskLog.Add(this._taskLog); } else { this._taskLog = this._databaseContext.ScheduledTaskLog.Where(log => log.ScheduledTask == this._scheduledTask.Id).OrderByDescending(log => log.StartTime).FirstOrDefault(); if (this._taskLog == null) { throw new AuctionMasterTaskException(ExceptionType.WARNING, "Last log not found"); } } this._databaseContext.SaveChanges(); this._databaseTransaction.Commit(); this._logService = new ScheduledTaskLogService(this.GetType(), this._taskLog); this._logService.start(); this._logService.writeLine(LogType.INFO, $"Scheduled task [{this._scheduledTask.Name}] has started.", true); }
// == CONSTRUCTOR(S) // ====================================================================== public ScheduledTaskLogService(Type origin, ScheduledTaskLog log) { this._origin = origin; this._log = log; }
// == EVENT(S) // ====================================================================== private void onTimedEvent(object source, ElapsedEventArgs evtArgs) { try { this._cycleCount++; LogUtil.writeLog(this.GetType(), LogType.INFO, $"TASK ORCHESTRATION CYCLE ({this._cycleCount}) STARTED"); foreach (KeyValuePair <int, GenericScheduledTask> entry in this._scheduledTasks) { if (entry.Value.task.Enabled == 1) { if (entry.Value.state == ScheduledTaskState.IDLE) { if (entry.Value.task.SheduledTaskFrequencyNavigation.Id == 1 && entry.Value.task.ScheduledTaskInterval != null) { // INTERVAL ScheduledTaskLog lastTaskLog = null; using (var scope = this._scopeFactory.CreateScope()) { DatabaseContext databaseContext = scope.ServiceProvider.GetRequiredService <DatabaseContext>(); lastTaskLog = databaseContext.ScheduledTaskLog.Where(log => log.ScheduledTask == entry.Value.task.Id).OrderByDescending(log => log.StartTime).FirstOrDefault(); } if (lastTaskLog == null) { entry.Value.start(); } else { if ((DateTime.Now - lastTaskLog.StartTime).TotalSeconds > entry.Value.task.ScheduledTaskInterval.First().Interval) { entry.Value.start(); } } } } if (entry.Value.state == ScheduledTaskState.ERROR) { ScheduledTaskLog lastTaskLog = null; using (var scope = this._scopeFactory.CreateScope()) { DatabaseContext databaseContext = scope.ServiceProvider.GetRequiredService <DatabaseContext>(); lastTaskLog = databaseContext.ScheduledTaskLog.Where(log => log.ScheduledTask == entry.Value.task.Id).OrderByDescending(log => log.StartTime).FirstOrDefault(); } if (lastTaskLog != null) { if (lastTaskLog.Tentatives < entry.Value.task.MaxTentatives) { entry.Value.start(); } else { entry.Value.state = ScheduledTaskState.IDLE; LogUtil.writeLog(this.GetType(), LogType.WARNING, $"Scheduled task '{entry.Value.task.Name}' has excceded the max number of tentatives to execution ({entry.Value.task.MaxTentatives})"); } } else { entry.Value.state = ScheduledTaskState.DEAD; throw new AuctionMasterTaskException(ExceptionType.FATAL, $"Scheduled task '{entry.Value.task.Name}' has thrown an error in the last execution but no logs are written in database"); } } } } } catch (System.Exception e) { LogUtil.writeLog(this.GetType(), LogType.WARNING, $"Error occured during execution of cycle {this._cycleCount}"); } }
private async Task RunDbTasks() { using (var scope = _serviceProvider.CreateScope()) { var taskRepository = scope.ServiceProvider.GetRequiredService <ScheduledTaskRepository> (); var applicationWrapper = scope.ServiceProvider.GetRequiredService <ConsoleApplicationWrapper <MinecraftMessageParser> > (); foreach (var task in _scheduledTasks.Where(task => task.Enabled)) { CrontabSchedule schedule = null; try { schedule = CrontabSchedule.Parse(task.CronString); } catch (CrontabException ex) { Log.Error(ex, $"Error occurred while running ScheduledTaskId={task.ScheduledTaskId}"); continue; } // In this one instance we're going to use server local time, because that's // how an end user would expect the app to work and timezones are hard. var next = schedule.GetNextOccurrence(DateTime.Now.AddMinutes(-1)); if (DateTime.Now >= next) { var lastLog = await taskRepository.GetLastLogForTask(task.ScheduledTaskId); if (lastLog == null || lastLog.StartTime < next) { var nextLog = new ScheduledTaskLog { StartTime = DateTime.Now, ScheduledTaskId = task.ScheduledTaskId }; await taskRepository.SaveScheduledTaskLogAsync(nextLog); try { switch (task.ScheduledTaskType) { case ScheduledTaskType.Backup: await CreateBackup(false); break; case ScheduledTaskType.Command: applicationWrapper.SendInput(task.Command, null); break; } nextLog.CompletedTime = DateTime.Now; nextLog.CompletionStatus = "SUCCESS"; await taskRepository.SaveScheduledTaskLogAsync(nextLog); } catch (Exception ex) { Log.Error(ex, $"Exception occurred while running ScheduledTaskId={task.ScheduledTaskId}"); nextLog.CompletedTime = DateTime.Now; nextLog.CompletionStatus = "FAILED"; await taskRepository.SaveScheduledTaskLogAsync(nextLog); } } } } } }