1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397
| #nullable enable using System; using System.Collections.Generic; using System.Threading;
public sealed class TimeWheel : IDisposable { #region Constants and Structs
private const int TVN_BITS = 6; private const int TVR_BITS = 8; private const int TVN_SIZE = 1 << TVN_BITS; private const int TVR_SIZE = 1 << TVR_BITS; private const int TVN_MASK = TVN_SIZE - 1; private const int TVR_MASK = TVR_SIZE - 1;
public const long MAX_DELAY = (long)TVR_SIZE * TVN_SIZE * TVN_SIZE * TVN_SIZE * TVN_SIZE - 1;
private class TimerTask { public ulong Id; public long ExecuteOrder; public Action<object?>? Callback; public object? Data; public ulong ExpireTicks; public ulong Interval; public int RepeatCount; public TimerTask? Next; public TimerTask? Prev;
public int State; }
#endregion
#region Core Fields
private readonly TimerTask?[] tv1 = new TimerTask[TVR_SIZE]; private readonly TimerTask?[] tv2 = new TimerTask[TVN_SIZE]; private readonly TimerTask?[] tv3 = new TimerTask[TVN_SIZE]; private readonly TimerTask?[] tv4 = new TimerTask[TVN_SIZE]; private readonly TimerTask?[] tv5 = new TimerTask[TVN_SIZE];
private ulong nextId; private long executeOrder; private ulong currentTick; private readonly bool shouldSortBeforeExecution; private readonly object syncRoot = new(); private readonly Stack<TimerTask?> taskPool = new(1024); private readonly List<TimerTask> taskListCache = new(1024);
#endregion
#region Public Interface
public static TimeWheel SharedInstance { get; private set; } = null!;
public static TimeWheel CreateSharedInstance(bool shouldSortBeforeExecution = true) { if (SharedInstance != null) { throw new Exception("SharedInstance already created"); }
return SharedInstance = new(shouldSortBeforeExecution); }
public TimeWheel(bool shouldSortBeforeExecution = true) { this.shouldSortBeforeExecution = shouldSortBeforeExecution; }
public event Action<Exception>? OnCallbackError;
public ulong Schedule(Action<object?> callback, ulong delay, ulong interval = 0, int repeatCount = 0, object? data = null) { if (callback == null) throw new ArgumentNullException(nameof(callback)); delay = delay switch { > MAX_DELAY => throw new ArgumentOutOfRangeException(nameof(delay), $"Delay must be less than {MAX_DELAY}, but got {delay}"), 0 => 1, _ => delay };
if (repeatCount != 0 && interval <= 0) throw new ArgumentOutOfRangeException(nameof(interval), $"Interval must be greater than zero");
var task = this.AllocateTask(); task.Id = ++this.nextId; task.ExecuteOrder = Interlocked.Increment(ref this.executeOrder); task.Callback = callback; task.Data = data; task.Interval = interval; task.RepeatCount = repeatCount; task.ExpireTicks = this.currentTick + delay;
lock (this.syncRoot) { this.InternalAddTask(task); }
return task.Id; }
public bool Cancel(ulong id) { lock (this.syncRoot) { foreach (var vec in new[] { this.tv1, this.tv2, this.tv3, this.tv4, this.tv5 }) { for (int i = 0; i < vec.Length; i++) { TimerTask? current = vec[i]; while (current != null) { if (current.Id == id) { if (Interlocked.CompareExchange(ref current.State, 2, 1) == 1) { RemoveTask(ref vec[i], current); this.ReleaseTask(current); return true; }
return false; }
current = current.Next; } } }
return false; } }
public void Dispose() { }
public void Tick() { lock (this.syncRoot) { this.TimeWheelWorker(); } }
#endregion
#region Core Algorithm
private void TimeWheelWorker() { if (this.currentTick >= long.MaxValue - 1) this.currentTick = 0; else this.currentTick++;
int index = (int)(this.currentTick & TVR_MASK); if (index == 0) { index = (int)(this.currentTick >> TVR_BITS) & TVN_MASK; this.CascadeTimers(this.tv2, index); if (index == 0) { index = (int)((this.currentTick >> (TVR_BITS + TVN_BITS)) & TVN_MASK); this.CascadeTimers(this.tv3, index); if (index == 0) { index = (int)((this.currentTick >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK); this.CascadeTimers(this.tv4, index); if (index == 0) { index = (int)((this.currentTick >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK); this.CascadeTimers(this.tv5, index); } } } }
this.ProcessTimers(ref this.tv1[this.currentTick & TVR_MASK]); }
private void CascadeTimers(TimerTask?[] tv, int index) { TimerTask? current = tv[index]; tv[index] = null;
while (current != null) { TimerTask? next = current.Next; this.InternalAddTask(current); current = next; } }
private void ProcessTimers(ref TimerTask? head) { var taskList = this.taskListCache; ExtractTasks(ref head, taskList); if (taskList.Count == 0) return;
if (taskList.Count > 1 && this.shouldSortBeforeExecution) taskList.Sort((a, b) => a.ExecuteOrder.CompareTo(b.ExecuteOrder));
foreach (var task in taskList) { if (task.State == 1 && this.currentTick >= task.ExpireTicks) { try { task.Callback?.Invoke(task.Data); } catch (Exception ex) { if (this.OnCallbackError != null) { this.OnCallbackError.Invoke(ex); } else { throw; } }
if (task.RepeatCount != 0) { if (task.RepeatCount > 0) task.RepeatCount--;
task.ExpireTicks += task.Interval; task.ExecuteOrder = Interlocked.Increment(ref this.executeOrder);
lock (this.syncRoot) { this.InternalAddTask(task); } } else { this.ReleaseTask(task); } } else if (task.State == 2) { this.ReleaseTask(task); } }
taskList.Clear(); }
private static void ExtractTasks(ref TimerTask? head, List<TimerTask> taskList) { TimerTask? current = head; while (current != null) { var next = current.Next; taskList.Add(current); current.Next = null; current.Prev = null; current = next; }
head = null; }
private void InternalAddTask(TimerTask task) { if (Interlocked.CompareExchange(ref task.State, 1, 1) == 2) return; var expires = task.ExpireTicks; var idx = expires - this.currentTick;
int i; TimerTask?[] vec; if (idx < TVR_SIZE) { i = (int)(expires & TVR_MASK); vec = this.tv1; } else if (idx < (1 << (TVR_BITS + TVN_BITS))) { i = (int)((expires >> TVR_BITS) & TVN_MASK); vec = this.tv2; } else if (idx < (1 << (TVR_BITS + 2 * TVN_BITS))) { i = (int)((expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK); vec = this.tv3; } else if (idx < (1 << (TVR_BITS + 3 * TVN_BITS))) { i = (int)((expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK); vec = this.tv4; } else { i = (int)((expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK); vec = this.tv5; } task.Prev = null; task.Next = null;
var oldTask = vec[i]; if (oldTask != null) { oldTask.Prev = task; task.Next = oldTask; }
vec[i] = task; task.State = 1; }
#endregion
#region Memory Management
private TimerTask AllocateTask() { lock (this.taskPool) { return this.taskPool.Count > 0 ? this.taskPool.Pop()! : new(); } }
private void ReleaseTask(TimerTask task) { Interlocked.Exchange(ref task.State, 2); task.Id = 0; task.ExecuteOrder = 0; task.Callback = null; task.Data = null; task.ExpireTicks = 0; task.Interval = 0; task.RepeatCount = 0; task.Next = null; task.Prev = null; task.State = 0;
lock (this.taskPool) { if (this.taskPool.Count < 1024) this.taskPool.Push(task); } }
#endregion
#region Helpers
private static void RemoveTask(ref TimerTask? head, TimerTask task) { if (task.Prev != null) task.Prev.Next = task.Next; else head = task.Next;
if (task.Next != null) task.Next.Prev = task.Prev; task.Next = null; task.Prev = null; }
#endregion }
|