초기커밋
This commit is contained in:
71
ServerBase/Manager/DailyTimeEventManager.cs
Normal file
71
ServerBase/Manager/DailyTimeEventManager.cs
Normal file
@@ -0,0 +1,71 @@
|
||||
using ServerCore; using ServerBase;
|
||||
|
||||
|
||||
namespace ServerBase;
|
||||
|
||||
public class DailyTimeTask
|
||||
{
|
||||
public Func<Task> m_task { get; init; } = null!;
|
||||
public DateTime m_time { get; init; } = DateTimeHelper.MinTime;
|
||||
public bool m_is_first_run { get; set; } = false;
|
||||
}
|
||||
|
||||
public class DailyTimeEventManager
|
||||
{
|
||||
private static readonly Lazy<DailyTimeEventManager> m_instance = new(() => new DailyTimeEventManager());
|
||||
public static DailyTimeEventManager Instance => m_instance.Value;
|
||||
|
||||
private Dictionary<string, DailyTimeTask> m_tasks { get; set; } = new();
|
||||
|
||||
public Result tryAddTask(string taskName, DateTime time, Func<Task> task, bool isFirstRun = false)
|
||||
{
|
||||
var result = new Result();
|
||||
|
||||
var is_add = m_tasks.TryAdd(taskName, new DailyTimeTask { m_task = task, m_time = time, m_is_first_run = isFirstRun});
|
||||
if (! is_add)
|
||||
{
|
||||
var err_msg = $"fail to add daily time event !! already added - taskName: {taskName} / time: {time}";
|
||||
result.setFail(ServerErrorCode.DailyTimeEventAdditionFailed, err_msg);
|
||||
Log.getLogger().error(result.toBasicString());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
public async Task runTimeEvents()
|
||||
{
|
||||
try
|
||||
{
|
||||
foreach (var task in m_tasks)
|
||||
{
|
||||
if (!checkEventTime(task.Value.m_time) && task.Value.m_is_first_run) continue;
|
||||
m_tasks[task.Key].m_is_first_run = true;
|
||||
|
||||
// fire and forget
|
||||
_ = Task.Run(task.Value.m_task);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
var err_msg = $"fail to run daily time event !! - {e}";
|
||||
Log.getLogger().error(err_msg);
|
||||
}
|
||||
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
private bool checkEventTime(DateTime time)
|
||||
{
|
||||
var current = DateTimeHelper.Current;
|
||||
|
||||
// Hour check
|
||||
if (current.Hour != time.Hour) return false;
|
||||
|
||||
// Minute check
|
||||
if (current.Minute != time.Minute) return false;
|
||||
|
||||
// seconds check
|
||||
if (current.Second != time.Second) return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user