Files
SfeduSchedule/SfeduSchedule/Services/ModeusEmployeeService.cs
Sergey Karmanov 46c50dc8e2 feat: Ввел персистентное хранение сотрудников
Реализовал загрузку списка сотрудников с диска при запуске службы.
Добавил методы для сохранения и загрузки сотрудников в файл.
2026-02-01 08:35:24 +03:00

80 lines
2.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using Quartz;
using SfeduSchedule.Jobs;
using System.Text.Json;
namespace SfeduSchedule.Services;
public class ModeusEmployeeService(ISchedulerFactory schedulerFactory)
: IHostedService
{
private Dictionary<string, (string, List<string>)> _employees = [];
private Task? _backgroundTask;
private CancellationTokenSource? _cts;
private readonly string _employeesFilePath = Path.Combine(Path.Combine(AppContext.BaseDirectory, AppConsts.DataFolderName), AppConsts.EmployeesFileName);
public async Task<Dictionary<string, (string, List<string>)>> GetEmployees(string fullname, int size = 10)
{
return _employees
.Where(e => e.Key.Contains(fullname, StringComparison.OrdinalIgnoreCase))
.Take(size)
.ToDictionary(e => e.Key, e => e.Value);
}
public bool IsInitialized()
{
return _employees.Count > 0;
}
public Task StartAsync(CancellationToken cancellationToken)
{
_cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
_backgroundTask = Task.Run(async () =>
{
// Загрузка с диска
await LoadEmployeesFromDisk();
}, _cts.Token);
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
if (_cts is null || _backgroundTask is null)
{
return;
}
_cts.Cancel();
try
{
await Task.WhenAny(_backgroundTask, Task.Delay(TimeSpan.FromSeconds(5), cancellationToken));
}
catch (OperationCanceledException)
{
// ignore
}
}
public async Task SetEmployees(Dictionary<string, (string, List<string>)> employees)
{
_employees = employees;
await SaveEmployeesToDisk();
}
private async Task LoadEmployeesFromDisk()
{
if (File.Exists(_employeesFilePath))
{
var json = await File.ReadAllTextAsync(_employeesFilePath);
_employees = JsonSerializer.Deserialize<Dictionary<string, (string, List<string>)>>(json) ?? new Dictionary<string, (string, List<string>)>();
}
}
private async Task SaveEmployeesToDisk()
{
var json = JsonSerializer.Serialize(_employees, new JsonSerializerOptions { WriteIndented = false });
await File.WriteAllTextAsync(_employeesFilePath, json);
}
}