forked from grandnode/grandnode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BackgroundServiceTask.cs
87 lines (82 loc) · 3.9 KB
/
BackgroundServiceTask.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using Grand.Core.Domain.Tasks;
using Grand.Services.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Grand.Services.Tasks
{
public class BackgroundServiceTask : BackgroundService
{
private readonly IServiceProvider _serviceProvider;
private ScheduleTask _task;
public BackgroundServiceTask(ScheduleTask task, IServiceProvider serviceProvider)
{
_task = task;
_serviceProvider = serviceProvider;
}
public override Task StartAsync(CancellationToken cancellationToken)
{
return base.StartAsync(cancellationToken);
}
public override Task StopAsync(CancellationToken cancellationToken)
{
return base.StopAsync(cancellationToken);
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
using (var scope = _serviceProvider.CreateScope())
{
var serviceProvider = scope.ServiceProvider;
var logger = serviceProvider.GetService<ILogger>();
var scheduleTaskService = serviceProvider.GetService<IScheduleTaskService>();
var task = await scheduleTaskService.GetTaskById(_task.Id);
var machineName = Environment.MachineName;
var timeInterval = task.TimeInterval > 0 ? task.TimeInterval : 1;
if (task.Enabled && (string.IsNullOrEmpty(task.LeasedByMachineName) || (machineName == task.LeasedByMachineName)))
{
var typeofTask = Type.GetType(_task.Type);
if (typeofTask != null)
{
var scheduleTask = serviceProvider.GetServices<IScheduleTask>().FirstOrDefault(x => x.GetType() == typeofTask);
if (scheduleTask != null)
{
task.LastStartUtc = DateTime.UtcNow;
try
{
await scheduleTask.Execute();
task.LastSuccessUtc = DateTime.UtcNow;
task.LastNonSuccessEndUtc = null;
}
catch (Exception exc)
{
task.LastNonSuccessEndUtc = DateTime.UtcNow;
task.Enabled = !task.StopOnError;
await logger.InsertLog(Core.Domain.Logging.LogLevel.Error, $"Error while running the '{task.ScheduleTaskName}' schedule task", exc.Message);
}
}
else
{
task.Enabled = !task.StopOnError;
task.LastNonSuccessEndUtc = DateTime.UtcNow;
await logger.InsertLog(Core.Domain.Logging.LogLevel.Error, $"Type {_task.Type} is not registered");
}
}
else
{
task.Enabled = !task.StopOnError;
task.LastNonSuccessEndUtc = DateTime.UtcNow;
await logger.InsertLog(Core.Domain.Logging.LogLevel.Error, $"Type {_task.Type} is null (type not exists)");
}
}
await scheduleTaskService.UpdateTask(task);
await Task.Delay(TimeSpan.FromMinutes(timeInterval), stoppingToken);
}
}
}
}
}