using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace JY.Model.Common
{
///
/// 定时任务管理器
///
public class TaskScheduler : IDisposable
{
private readonly ConcurrentDictionary _tasks
= new ConcurrentDictionary();
///
/// 添加一个新任务
///
public Guid AddTask(TimerCallback callback, int interval, object state = null)
{
var taskId = Guid.NewGuid();
var task = new ScheduledTask(taskId, callback, interval, state);
_tasks[taskId] = task;
task.Start();
return taskId;
}
///
/// 移除一个任务
///
public bool RemoveTask(Guid taskId)
{
if (_tasks.TryRemove(taskId, out var task))
{
task.Dispose();
return true;
}
return false;
}
///
/// 修改任务间隔
///
public bool ChangeInterval(Guid taskId, int newInterval)
{
if (_tasks.TryGetValue(taskId, out var task))
{
task.ChangeInterval(newInterval);
return true;
}
return false;
}
///
/// 停止所有任务
///
public void StopAll()
{
foreach (var task in _tasks.Values)
{
task.Stop();
}
}
public void Dispose()
{
StopAll();
foreach (var task in _tasks.Values)
{
task.Dispose();
}
_tasks.Clear();
}
}
}