public void Test_執行排程備份_schedule設定為現在時間_應會產生三個檔案() { // arrange // 產生測試用檔案 string filePath = "D:\\Projects\\oop-homework\\storage\\app\\ScheduledTaskTest.txt6"; File.WriteAllText(filePath, "123"); // 測試執行時預期產生的檔案 string byteArrayToFile = "D:\\Projects\\oop-homework\\storage\\app\\ScheduledTaskTest.txt6.backup"; // 測試完預期產生的檔案 string copyToNewFile = "D:\\Projects\\oop-homework\\storage\\app\\backup\\ScheduledTaskTest.txt6.backup"; // act scheduledTask.Execute(CreateFakeConfig(), CreateFakeScheduleCanExecute()); // assert // 查看是否有檔案產生 Assert.True(File.Exists(filePath)); Assert.True(File.Exists(byteArrayToFile)); Assert.True(File.Exists(copyToNewFile)); // 測試結束刪除檔案 File.Delete(filePath); File.Delete(byteArrayToFile); File.Delete(copyToNewFile); Assert.False(File.Exists(filePath)); Assert.False(File.Exists(byteArrayToFile)); Assert.False(File.Exists(copyToNewFile)); }
private async Task ExecuteInternal(TaskExecutionOptions options) { // Cancel the current execution, if any if (CurrentCancellationTokenSource != null) { throw new InvalidOperationException("Cannot execute a Task that is already running"); } var progress = new SimpleProgress <double>(); CurrentCancellationTokenSource = new CancellationTokenSource(); Logger.Info("Executing {0}", Name); ((TaskManager)TaskManager).OnTaskExecuting(this); progress.ProgressChanged += progress_ProgressChanged; TaskCompletionStatus status; CurrentExecutionStartTime = DateTime.UtcNow; Exception failureException = null; try { if (options != null && options.MaxRuntimeMs.HasValue) { CurrentCancellationTokenSource.CancelAfter(options.MaxRuntimeMs.Value); } var localTask = ScheduledTask.Execute(CurrentCancellationTokenSource.Token, progress); await localTask.ConfigureAwait(false); status = TaskCompletionStatus.Completed; } catch (OperationCanceledException) { status = TaskCompletionStatus.Cancelled; } catch (Exception ex) { Logger.ErrorException("Error", ex); failureException = ex; status = TaskCompletionStatus.Failed; } var startTime = CurrentExecutionStartTime; var endTime = DateTime.UtcNow; progress.ProgressChanged -= progress_ProgressChanged; CurrentCancellationTokenSource.Dispose(); CurrentCancellationTokenSource = null; CurrentProgress = null; OnTaskCompleted(startTime, endTime, status, failureException); }
/// <summary> /// Executes the task. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <param name="progress">The progress.</param> /// <returns>Task.</returns> private Task ExecuteTask(CancellationToken cancellationToken, IProgress <double> progress) { return(Task.Run(async() => await ScheduledTask.Execute(cancellationToken, progress).ConfigureAwait(false), cancellationToken)); }