增加定时任务

This commit is contained in:
liming 蔡
2026-07-21 19:37:29 +08:00
parent 127da277e0
commit af014ed33c
8 changed files with 182 additions and 20 deletions
+55
View File
@@ -0,0 +1,55 @@
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace JY.Model.Common
{
public class ScheduledTask : IDisposable
{
private Timer _timer;
private readonly TimerCallback _callback;
private readonly object _state;
public Guid TaskId { get; }
public int Interval { get; private set; } // 毫秒
public bool IsRunning { get; private set; }
public ScheduledTask(Guid taskId, TimerCallback callback, int interval, object state = null)
{
TaskId = taskId;
_callback = callback;
Interval = interval;
_state = state;
IsRunning = false;
}
public void Start()
{
if (IsRunning) return;
_timer = new Timer(_callback, _state, 0, Interval);
IsRunning = true;
}
public void ChangeInterval(int newInterval)
{
Interval = newInterval;
if (IsRunning && _timer != null)
{
_timer.Change(0, newInterval);
}
}
public void Stop()
{
if (!IsRunning) return;
_timer?.Change(Timeout.Infinite, Timeout.Infinite);
IsRunning = false;
}
public void Dispose()
{
Stop();
_timer?.Dispose();
}
}
}