cron.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #include "cron.h"
  2. #include <library/cpp/deprecated/atomic/atomic.h>
  3. #include <util/system/thread.h>
  4. #include <util/system/event.h>
  5. using namespace NCron;
  6. namespace {
  7. struct TPeriodicHandle: public IHandle {
  8. inline TPeriodicHandle(TJob job, TDuration interval, const TString& threadName)
  9. : Job(job)
  10. , Interval(interval)
  11. , Done(false)
  12. {
  13. TThread::TParams params(DoRun, this);
  14. if (!threadName.empty()) {
  15. params.SetName(threadName);
  16. }
  17. Thread = MakeHolder<TThread>(params);
  18. Thread->Start();
  19. }
  20. static inline void* DoRun(void* data) noexcept {
  21. ((TPeriodicHandle*)data)->Run();
  22. return nullptr;
  23. }
  24. inline void Run() noexcept {
  25. while (true) {
  26. Job();
  27. Event.WaitT(Interval);
  28. if (AtomicGet(Done)) {
  29. return;
  30. }
  31. }
  32. }
  33. ~TPeriodicHandle() override {
  34. AtomicSet(Done, true);
  35. Event.Signal();
  36. Thread->Join();
  37. }
  38. TJob Job;
  39. TDuration Interval;
  40. TManualEvent Event;
  41. TAtomic Done;
  42. THolder<TThread> Thread;
  43. };
  44. }
  45. IHandlePtr NCron::StartPeriodicJob(TJob job) {
  46. return NCron::StartPeriodicJob(job, TDuration::Seconds(0), "");
  47. }
  48. IHandlePtr NCron::StartPeriodicJob(TJob job, TDuration interval) {
  49. return NCron::StartPeriodicJob(job, interval, "");
  50. }
  51. IHandlePtr NCron::StartPeriodicJob(TJob job, TDuration interval, const TString& threadName) {
  52. return new TPeriodicHandle(job, interval, threadName);
  53. }
  54. IHandle::~IHandle() = default;