timer_queue_test.cc 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Portions Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
  2. // This source code is licensed under both the GPLv2 (found in the
  3. // COPYING file in the root directory) and Apache 2.0 License
  4. // (found in the LICENSE.Apache file in the root directory).
  5. // borrowed from
  6. // http://www.crazygaze.com/blog/2016/03/24/portable-c-timer-queue/
  7. // Timer Queue
  8. //
  9. // License
  10. //
  11. // The source code in this article is licensed under the CC0 license, so feel
  12. // free
  13. // to copy, modify, share, do whatever you want with it.
  14. // No attribution is required, but Ill be happy if you do.
  15. // CC0 license
  16. // The person who associated a work with this deed has dedicated the work to the
  17. // public domain by waiving all of his or her rights to the work worldwide
  18. // under copyright law, including all related and neighboring rights, to the
  19. // extent allowed by law. You can copy, modify, distribute and perform the
  20. // work, even for
  21. // commercial purposes, all without asking permission. See Other Information
  22. // below.
  23. //
  24. #include "util/timer_queue.h"
  25. #include <future>
  26. namespace Timing {
  27. using Clock = std::chrono::high_resolution_clock;
  28. double now() {
  29. static auto start = Clock::now();
  30. return std::chrono::duration<double, std::milli>(Clock::now() - start)
  31. .count();
  32. }
  33. } // namespace Timing
  34. int main() {
  35. TimerQueue q;
  36. double tnow = Timing::now();
  37. q.add(10000, [tnow](bool aborted) mutable {
  38. printf("T 1: %d, Elapsed %4.2fms\n", aborted, Timing::now() - tnow);
  39. return std::make_pair(false, 0);
  40. });
  41. q.add(10001, [tnow](bool aborted) mutable {
  42. printf("T 2: %d, Elapsed %4.2fms\n", aborted, Timing::now() - tnow);
  43. return std::make_pair(false, 0);
  44. });
  45. q.add(1000, [tnow](bool aborted) mutable {
  46. printf("T 3: %d, Elapsed %4.2fms\n", aborted, Timing::now() - tnow);
  47. return std::make_pair(!aborted, 1000);
  48. });
  49. auto id = q.add(2000, [tnow](bool aborted) mutable {
  50. printf("T 4: %d, Elapsed %4.2fms\n", aborted, Timing::now() - tnow);
  51. return std::make_pair(!aborted, 2000);
  52. });
  53. (void)id;
  54. // auto ret = q.cancel(id);
  55. // assert(ret == 1);
  56. // q.cancelAll();
  57. return 0;
  58. }
  59. //////////////////////////////////////////