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(); } } }