Designing a custom scheduler
Usually, all the needed schedulers already exists. Although, sometimes, it may happen that we may need a custom scheduler because we may need to choose how to schedule our jobs by ourselves. In the next example, we will see how to create a scheduler to throttle message flowing based on the CPU time. The CpuThrottlingScheduler
method will verify each message flowing if the CPU time is at the desired level. Then, eventually, the observer's implementation will receive the message in the context thread of the ThreadPool
thread to achieve multithreading if multiple subscribers exist.
Here is the scheduler code:
/// <summary> /// Enqueues unit of works only if the current CPU time is lower than the /// specified limit. /// </summary> public class CpuThrottlingScheduler : IScheduler, IDisposable { public int CpuLimitPercentage { get; set; } = 80; public DateTimeOffset Now { get; private set; } ...