1
0

新增方法練習顯示處理進度

This commit is contained in:
2024-03-18 10:43:42 +08:00
parent ea4e5da703
commit e55b957028
6 changed files with 52 additions and 5 deletions

View File

@@ -1,6 +1,8 @@
using Hangfire;
using Hangfire.Console;
using Hangfire.PerformContextAccessor;
using Hangfire.Server;
using HangfireExample.WebService.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel;
@@ -10,7 +12,12 @@ namespace HangfireExample.WebService.Controllers
[ApiController]
public class JobController : ControllerBase, IJobService
{
public JobController() { }
public JobController(IPerformContextAccessor perform)
{
this.perform = perform;
}
private readonly IPerformContextAccessor perform;
[HttpPost("Continuation", Name = "Continuation"), Produces("application/json")]
public string Continuation(string message, string jobId)
@@ -72,5 +79,37 @@ namespace HangfireExample.WebService.Controllers
{
Console.WriteLine("{0}: {1}", DateTimeOffset.Now, message);
}
[HttpPost("Progress", Name = "Progress"), Produces("application/json")]
public string Progress(int seconds)
{
return BackgroundJob.Enqueue(() => ProgressJob(perform.PerformingContext, seconds));
}
[NonAction]
[DisplayName("Progress, Seconds = {1}")]
public void ProgressJob(PerformContext context, int seconds)
{
var bar = context.WriteProgressBar();
context.WriteLine("The text color change to red");
context.SetTextColor(ConsoleTextColor.Red);
context.WriteLine("This progress is ready to start");
context.ResetTextColor();
foreach (var i in Enumerable.Range(0, seconds).ToList().WithProgress(bar))
{
Thread.Sleep(1000);
}
context.SetTextColor(ConsoleTextColor.Green);
context.WriteLine("This progress has finished");
context.ResetTextColor();
}
}
}