BDE 4.39.x Production Release
Loading...
Searching...
No Matches
bdlt_currenttime.h
Go to the documentation of this file.
1/// @file bdlt_currenttime.h
2///
3/// The content of this file has been pre-processed for Doxygen.
4///
5
6
7// bdlt_currenttime.h -*-C++-*-
8#ifndef INCLUDED_BDLT_CURRENTTIME
9#define INCLUDED_BDLT_CURRENTTIME
10
11#include <bsls_ident.h>
12BSLS_IDENT("$Id: $")
13
14/// @defgroup bdlt_currenttime bdlt_currenttime
15/// @brief Provide utilities to retrieve the current time.
16/// @addtogroup bdl
17/// @{
18/// @addtogroup bdlt
19/// @{
20/// @addtogroup bdlt_currenttime
21/// @{
22///
23/// <h1> Outline </h1>
24/// * <a href="#bdlt_currenttime-purpose"> Purpose</a>
25/// * <a href="#bdlt_currenttime-classes"> Classes </a>
26/// * <a href="#bdlt_currenttime-description"> Description </a>
27/// * <a href="#bdlt_currenttime-thread-safety"> Thread Safety </a>
28/// * <a href="#bdlt_currenttime-usage"> Usage </a>
29/// * <a href="#bdlt_currenttime-example-1-repeatable-tests-involving-current-time"> Example 1: Repeatable Tests Involving Current Time </a>
30///
31/// # Purpose {#bdlt_currenttime-purpose}
32/// Provide utilities to retrieve the current time.
33///
34/// # Classes {#bdlt_currenttime-classes}
35///
36/// - bdlt::CurrentTime: namespace for current-time procedures
37///
38/// @see bsls_timeinterval, bdlt_systemtimeutil
39///
40/// # Description {#bdlt_currenttime-description}
41/// This component, `bdlt::CurrentTime`, provides static methods
42/// for retrieving the current time in Coordinated Universal Time (UTC) and in
43/// the local time zone of the executing process. It also provides a facility
44/// for customizing the means by which the time is retrieved.
45///
46/// ## Thread Safety {#bdlt_currenttime-thread-safety}
47///
48///
49/// The functions provided by `bdlt::CurrentTime` are *thread-safe* (meaning
50/// they may be called concurrently from multiple threads), including those that
51/// set and retrieve the callback function. In addition, user-supplied callback
52/// functions must be *thread-safe*.
53///
54/// ## Usage {#bdlt_currenttime-usage}
55///
56///
57/// This section illustrates intended use of this component.
58///
59/// ### Example 1: Repeatable Tests Involving Current Time {#bdlt_currenttime-example-1-repeatable-tests-involving-current-time}
60///
61///
62/// Suppose we are writing an application which involves dealing with the
63/// current time (for example, a clock displaying it). In order to test the
64/// application, we would like to be able to control the time it sees. We can
65/// use `bdlt::CurrentTime` for this purpose.
66///
67/// First, we create a sample application. For this example, we simply have it
68/// retrieve the current time in several formats:
69/// @code
70/// /// Retrieve versions of the current time into the specified `local`, `utc`,
71/// /// and `now` parameters.
72/// void sampleApplication(bdlt::Datetime *local,
73/// bdlt::Datetime *utc,
74/// bsls::TimeInterval *now)
75/// {
76/// *local = bdlt::CurrentTime::local();
77/// *utc = bdlt::CurrentTime::utc();
78/// *now = bdlt::CurrentTime::now();
79/// }
80/// @endcode
81/// Then, we create a method to test whether the application is producing the
82/// expected results:
83/// @code
84/// /// Return `true` iff `sampleApplication` returns values matching the
85/// /// specified expected values `expectedLocal`, `expectedUtc`, and
86/// /// `expectedNow`.
87/// bool checkApplication(bdlt::Datetime expectedLocal,
88/// bdlt::Datetime expectedUtc,
89/// bsls::TimeInterval expectedNow)
90/// {
91/// bdlt::Datetime local;
92/// bdlt::Datetime utc;
93/// bsls::TimeInterval now;
94///
95/// sampleApplication(&local, &utc, &now);
96/// return expectedLocal == local &&
97/// expectedUtc == utc &&
98/// expectedNow == now;
99/// }
100/// @endcode
101/// Next, we create a class allowing us to set the current time which will be
102/// seen by the application:
103/// @code
104/// /// Maintain and return a "current time" value.
105/// class TestCurrentTimeGuard {
106/// private:
107/// bdlt::CurrentTime::CurrentTimeCallback d_prev; // old callback
108///
109/// public:
110/// /// Create an object of this type, installing the handler.
111/// TestCurrentTimeGuard();
112///
113/// /// Destroy an object of this type, restoring the handler.
114/// ~TestCurrentTimeGuard();
115///
116/// /// Return `s_time`.
117/// static bsls::TimeInterval time();
118///
119/// static bsls::TimeInterval s_time; // the "current time"
120/// };
121///
122/// bsls::TimeInterval TestCurrentTimeGuard::s_time;
123///
124/// TestCurrentTimeGuard::TestCurrentTimeGuard()
125/// : d_prev(bdlt::CurrentTime::setCurrentTimeCallback(time))
126/// {
127/// }
128///
129/// TestCurrentTimeGuard::~TestCurrentTimeGuard()
130/// {
131/// bdlt::CurrentTime::setCurrentTimeCallback(d_prev);
132/// }
133///
134/// bsls::TimeInterval TestCurrentTimeGuard::time()
135/// {
136/// return s_time;
137/// }
138/// @endcode
139/// Finally, we write a method that tests that our application is functioning
140/// correctly:
141/// @code
142/// /// Test the application.
143/// void testApplication()
144/// {
145/// TestCurrentTimeGuard tct;
146/// TestCurrentTimeGuard::s_time = bdlt::EpochUtil::convertToTimeInterval(
147/// bdlt::EpochUtil::epoch());
148///
149/// bdlt::Datetime local;
150/// bdlt::Datetime utc;
151/// bsls::TimeInterval now;
152///
153/// sampleApplication(&local, &utc, &now);
154///
155/// TestCurrentTimeGuard::s_time += 1E6;
156/// local.addSeconds(1000000);
157/// utc.addSeconds(1000000);
158/// now += 1E6;
159///
160/// assert(checkApplication(local, utc, now));
161/// }
162/// @endcode
163/// @}
164/** @} */
165/** @} */
166
167/** @addtogroup bdl
168 * @{
169 */
170/** @addtogroup bdlt
171 * @{
172 */
173/** @addtogroup bdlt_currenttime
174 * @{
175 */
176
177#include <bdlscm_version.h>
178
179#include <bdlt_datetime.h>
180#include <bdlt_datetimetz.h>
181#include <bdlt_epochutil.h>
182#include <bdlt_localtimeoffset.h>
183
184#include <bsls_assert.h>
186#include <bsls_timeinterval.h>
187#include <bsls_types.h>
188
189#ifndef BDE_DONT_ALLOW_TRANSITIVE_INCLUDES
191#endif // BDE_DONT_ALLOW_TRANSITIVE_INCLUDES
192
193
194namespace bdlt {
195
196 // ==================
197 // struct CurrentTime
198 // ==================
199
200/// This `struct` provides a namespace for current-time-retrieval procedures
201/// including a configurable global callback mechanism. The use of a
202/// *subset* of these procedures is thread-safe (see `Thread Safety`).
203///
204/// See @ref bdlt_currenttime
206 public:
207 // TYPES
208
209 /// `CurrentTimeCallback` is a callback function pointer for a callback
210 /// function that returns a `bsls::TimeInterval` object. This function
211 /// must be thread-safe in multi-threaded builds.
213
214 private:
215 static bsls::AtomicOperations::AtomicTypes::Pointer
216 s_currenttimeCallback_p;
217 // address of current-time callback
218
219 public:
220 // CLASS METHODS
221
222 // ** now functions **
223
224 /// Return the `Datetime` value representing the current date/time in
225 /// the local time zone, as provided by the installed callback function
226 /// and the facilities of `LocalTimeOffset`.
227 static Datetime local();
228
229 /// Return the `TimeInterval` value between `EpochUtil::epoch()` and the
230 /// current date/time as provided by the installed callback function.
231 ///
232 /// \note Note that this value is independent of time zone.
233 static bsls::TimeInterval now();
234
235 /// Return the `Datetime` value representing the current date/time in
236 /// Coordinated Universal Time (UTC) as provided by the installed
237 /// callback function.
238 static Datetime utc();
239
240 /// Return the `DatetimeTz` value representing the current date/time in
241 /// the local time zone, and the local time zone's offset from UTC, as
242 /// provided by the installed callback function and the facilities of
243 /// `LocalTimeOffset`.
245
246 // ** callback functions **
247
248 /// Return the installed function used to retrieve the interval between
249 /// `EpochUtil::epoch()` and the current date/time,
251
252 /// Set the specified `callback` as the function to be used to retrieve
253 /// the interval between `EpochUtil::epoch()` and the current date/time,
254 /// and return the previously set function.
257
258 // ** default callback function **
259
260 /// Return the `TimeInterval` value between `EpochUtil::epoch()` and the
261 /// current date/time. This is the default current-time callback
262 /// implementation for current time retrieval. The obtained time is
263 /// expressed as a time interval from `00:00 UTC, January 1, 1970`. The
264 /// resolution is:
265 /// * Unix DG-Unix: microsecond resolution
266 ///
267 /// * Linux: nanosecond resolution
268 ///
269 /// * Solaris: 5 nanosecond resolution
270 ///
271 /// * Windows 11: 1-5 millisecond resolution
273};
274
275// ============================================================================
276// INLINE DEFINITIONS
277// ============================================================================
278
279 // -----------------
280 // class CurrentTime
281 // -----------------
282
283// CLASS METHODS
284
285 // ** now functions **
286
287inline
289{
290 Datetime now = utc();
291
293
294 return now;
295}
296
297inline
302
303inline
305{
306 return EpochUtil::epoch() + now();
307}
308
309 // ** callback functions **
310
311inline
313{
314 return reinterpret_cast<CurrentTimeCallback>(
315 reinterpret_cast<bsls::Types::IntPtr>(
316 bsls::AtomicOperations::getPtrAcquire(&s_currenttimeCallback_p)));
317}
318
319inline
321CurrentTime::setCurrentTimeCallback(CurrentTimeCallback callback)
322{
323 BSLS_ASSERT_OPT(callback);
324
325 CurrentTimeCallback previousCallback = currentTimeCallback();
326
328 &s_currenttimeCallback_p,
329 reinterpret_cast<void *>(
330 reinterpret_cast<bsls::Types::IntPtr>(callback)));
331
332 return previousCallback;
333}
334
335} // close package namespace
336
337
338#endif
339
340// ----------------------------------------------------------------------------
341// Copyright 2016 Bloomberg Finance L.P.
342//
343// Licensed under the Apache License, Version 2.0 (the "License");
344// you may not use this file except in compliance with the License.
345// You may obtain a copy of the License at
346//
347// http://www.apache.org/licenses/LICENSE-2.0
348//
349// Unless required by applicable law or agreed to in writing, software
350// distributed under the License is distributed on an "AS IS" BASIS,
351// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
352// See the License for the specific language governing permissions and
353// limitations under the License.
354// ----------------------------- END-OF-FILE ----------------------------------
355
356/** @} */
357/** @} */
358/** @} */
Definition bdlt_datetimetz.h:308
Definition bdlt_datetime.h:330
Definition bsls_timeinterval.h:307
BSLS_KEYWORD_CONSTEXPR_CPP14 TimeInterval & addSeconds(bsls::Types::Int64 seconds)
Definition bsls_timeinterval.h:1197
#define BSLS_ASSERT_OPT(X)
Definition bsls_assert.h:2045
#define BSLS_IDENT(str)
BSLS_IDENT() - insert string into .comment binary segment (if supported)
Definition bsls_ident.h:238
Definition bbldc_basicisma30360.h:112
Definition bdlt_currenttime.h:205
static bsls::TimeInterval now()
Definition bdlt_currenttime.h:298
static DatetimeTz asDatetimeTz()
bsls::TimeInterval(* CurrentTimeCallback)()
Definition bdlt_currenttime.h:212
static bsls::TimeInterval currentTimeDefault()
static CurrentTimeCallback currentTimeCallback()
Definition bdlt_currenttime.h:312
static Datetime local()
Definition bdlt_currenttime.h:288
static CurrentTimeCallback setCurrentTimeCallback(CurrentTimeCallback callback)
Definition bdlt_currenttime.h:321
static Datetime utc()
Definition bdlt_currenttime.h:304
static const Datetime & epoch()
Definition bdlt_epochutil.h:397
static bsls::TimeInterval localTimeOffset(const Datetime &utcDatetime)
Definition bdlt_localtimeoffset.h:318
static void * getPtrAcquire(AtomicTypes::Pointer const *atomicPtr)
Definition bsls_atomicoperations.h:2314
static void setPtrRelease(AtomicTypes::Pointer *atomicPtr, void *value)
Definition bsls_atomicoperations.h:2347
std::ptrdiff_t IntPtr
Definition bsls_types.h:132