#pragma once #include #include #include #include #include #include #include class TTaskScheduler { public: class ITask; using ITaskRef = TIntrusivePtr; class IRepeatedTask; using IRepeatedTaskRef = TIntrusivePtr; public: explicit TTaskScheduler(size_t threadCount = 1, size_t maxTaskCount = Max()); ~TTaskScheduler(); void Start(); void Stop(); bool Add(ITaskRef task, TInstant expire); bool Add(IRepeatedTaskRef task, TDuration period); size_t GetTaskCount() const; private: class TWorkerThread; struct TTaskHolder { explicit TTaskHolder(ITaskRef& task) : Task(task) { } public: ITaskRef Task; TWorkerThread* WaitingWorker = nullptr; }; using TQueueType = TMultiMap; using TQueueIterator = TQueueType::iterator; private: void ChangeDebugState(TWorkerThread* thread, const TString& state); void ChooseFromQueue(TQueueIterator& toWait); bool Wait(TWorkerThread* thread, TQueueIterator& toWait); void WorkerFunc(TWorkerThread* thread); private: bool IsStopped_ = false; TAtomic TaskCounter_ = 0; TQueueType Queue_; TCondVar CondVar_; TMutex Lock_; TVector> Workers_; const size_t MaxTaskCount_; }; class TTaskScheduler::ITask : public TAtomicRefCount { public: virtual ~ITask(); virtual TInstant Process() {//returns time to repeat this task return TInstant::Max(); } }; class TTaskScheduler::IRepeatedTask : public TAtomicRefCount { public: virtual ~IRepeatedTask(); virtual bool Process() {//returns if to repeat task again return false; } };