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