mirror of
https://github.com/Megghy/MegghysAPI.git
synced 2025-12-06 22:26:56 +08:00
添加项目文件。
This commit is contained in:
50
Core/TimerManager.cs
Normal file
50
Core/TimerManager.cs
Normal file
@@ -0,0 +1,50 @@
|
||||
using System.Diagnostics;
|
||||
using System.Reflection;
|
||||
using MegghysAPI.Attributes;
|
||||
|
||||
namespace MegghysAPI.Core
|
||||
{
|
||||
public static class TimerManager
|
||||
{
|
||||
|
||||
private static Dictionary<MethodInfo, AutoTimerAttribute> timers = new();
|
||||
private static long time = 0;
|
||||
[AutoInit(Order = 100)]
|
||||
public static void RegisterAll()
|
||||
{
|
||||
System.Timers.Timer temp = new()
|
||||
{
|
||||
Interval = 1000,
|
||||
AutoReset = true,
|
||||
};
|
||||
temp.Elapsed += (_, _) =>
|
||||
{
|
||||
if (time != 0)
|
||||
timers.Where(timer => time % timer.Value.Time == 0)
|
||||
.ForEach(timer =>
|
||||
{
|
||||
Task.Run(() =>
|
||||
{
|
||||
var sw = new Stopwatch();
|
||||
sw.Start();
|
||||
timer.Key.Invoke(null, null);
|
||||
sw.Stop();
|
||||
if (timer.Value.Log)
|
||||
Logs.Text($"[{sw.ElapsedMilliseconds} ms] [{timer.Key.DeclaringType.Name}.{timer.Key.Name}] 计时器触发 [{timer.Value.Time}-{time}]");
|
||||
});
|
||||
});
|
||||
time++;
|
||||
};
|
||||
AppDomain.CurrentDomain.GetAssemblies()
|
||||
.ForEach(a => a.GetTypes().Where(t => t.IsClass).ForEach(t => t.GetMethods().Where(m => m.GetCustomAttributes(true).FirstOrDefault(a => a is AutoTimerAttribute) != null)
|
||||
.ForEach(m =>
|
||||
{
|
||||
var attr = m.GetCustomAttributes(true).FirstOrDefault(a => a is AutoTimerAttribute) as AutoTimerAttribute;
|
||||
timers.Add(m, attr);
|
||||
Logs.Info($"注册自动计时器 {m.DeclaringType.Name}.{m.Name} <{attr.Time} s>");
|
||||
})));
|
||||
temp.Start();
|
||||
timers.Where(timer => timer.Value.CallOnRegister).ForEach(timer => Task.Run(() => timer.Key.Invoke(null, null)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user