Music Hub  ..
A session-wide music playback service
timeout.h
Go to the documentation of this file.
1 /*
2  *
3  * This program is free software: you can redistribute it and/or modify it
4  * under the terms of the GNU Lesser General Public License version 3,
5  * as published by the Free Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU Lesser General Public License for more details.
11  *
12  * You should have received a copy of the GNU Lesser General Public License
13  * along with this program. If not, see <http://www.gnu.org/licenses/>.
14  *
15  * Authored by: Jim Hodapp <jim.hodapp@canonical.com>
16  *
17  * Adapted from: http://stackoverflow.com/questions/14650885/how-to-create-timer-events-using-c-11
18  *
19  */
20 
21 #ifndef TIMEOUT_H_
22 #define TIMEOUT_H_
23 
24 #include <functional>
25 #include <chrono>
26 #include <future>
27 #include <cstdio>
28 
29 namespace core
30 {
31 namespace ubuntu
32 {
33 namespace media
34 {
35 
36 class timeout
37 {
38 public:
46  template <class callable, class... arguments>
47  timeout(int timeout_ms, bool async, callable&& f, arguments&&... args)
48  {
49  std::function<typename std::result_of<callable(arguments...)>::type()>
50  task(std::bind(std::forward<callable>(f), std::forward<arguments>(args)...));
51 
52  if (async)
53  {
54  // Timeout without blocking
55  std::thread([timeout_ms, task]() {
56  std::this_thread::sleep_for(std::chrono::milliseconds(timeout_ms));
57  task();
58  }).detach();
59  }
60  else
61  {
62  // Timeout with blocking
63  std::this_thread::sleep_for(std::chrono::milliseconds(timeout_ms));
64  task();
65  }
66  }
67 };
68 
69 }
70 }
71 }
72 
73 #endif // TIMEOUT_H_
Definition: player.h:33
timeout(int timeout_ms, bool async, callable &&f, arguments &&...args)
Start a timeout with millisecond resolution.
Definition: timeout.h:47