You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

141 lines
3.5 KiB

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Office2010.Drawing;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Volo.Abp.Application.Services;
using Volo.Abp.Caching;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Win_in.Sfs.Basedata.Application.Contracts;
using Win_in.Sfs.Basedata.Domain;
using Win_in.Sfs.Basedata.Domain.Caches;
using Win_in.Sfs.Basedata.Domain.Shared;
namespace Win_in.Sfs.Basedata.Application;
public class TaskQueue
{
private readonly List<TaskItem> _tasks = new List<TaskItem>();
public void Enqueue(string name, Action action)
{
_tasks.Add(new TaskItem { Name = name, Action = action });
}
public async Task StartAsync()
{
foreach (var task in _tasks)
{
await Task.Run(task.Action).ConfigureAwait(false);
}
}
}
public class TaskItem
{
public string Name { get; set; }
public Action Action { get; set; }
}
public class CycleOptions
{
/// <summary>
/// Boms缓存生命周期(秒)
/// </summary>
public int BomsCycle { get; set; }
}
/// <summary>
/// 提供缓存服务的类(堵塞以后修改再用)
/// </summary>
public class CacheService:ISingletonDependency
{
private readonly IServiceProvider _serviceProvider;
private readonly IOptions<CycleOptions> _options;
public CacheService(IServiceProvider serviceProvider, IOptions<CycleOptions> options)
{
_serviceProvider = serviceProvider;
_options = options;
}
/// <summary>
/// 生命周期操作
/// </summary>
private async Task BomsCycle()
{
//Task.Run(async () =>
//{
var reassigner = new Reassigner(DateTime.Now, new TimeSpan(0, 0, _options.Value.BomsCycle == 0 ? 60 : _options.Value.BomsCycle));
await reassigner.RunAsync(async () =>
{
using var serviceScope = _serviceProvider.CreateScope();
var repository = serviceScope.ServiceProvider.GetRequiredService<IBomRepository>();
Cache.Boms.Clear();
Cache.Boms = await repository.GetListAsync().ConfigureAwait(false);
}).ConfigureAwait(false);
//});
;
}
/// <summary>
/// 异步开始生命周期操作不能堵塞
/// </summary>
public async Task StartAsync()
{
BomsCycle();//异步处理不能堵塞主任务
}
}
public class Reassigner
{
private readonly TimeSpan _interval;
private DateTime _lasttime;
public Reassigner(DateTime lasttime, TimeSpan interval)
{
_lasttime = lasttime;
_interval = interval;
}
public async Task RunAsync(Action p_action)
{
while (true)
{
// 获取当前时间
var currentTime = DateTime.Now;
// 计算上次重新赋值到现在的时间间隔
var elapsed = currentTime - _lasttime;
// 检查时间间隔是否满足条件
if (elapsed >= _interval)
{
p_action();
// 重新赋值
//_value = await GetValueAsync();
// 更新最后更新时间
_lasttime = currentTime;
}
// 等待下一刻钟
await Task.Delay(_interval).ConfigureAwait(false);
}
}
}