Outline
Purpose
Provide utilities to retrieve the current time.
Classes
- See also
- bsls_timeinterval, bdlt_systemtimeutil
Description
This component, bdlt::CurrentTime
, provides static methods for retrieving the current time in Coordinated Universal Time (UTC) and in the local time zone of the executing process. It also provides a facility for customizing the means by which the time is retrieved.
Thread Safety
The functions provided by bdlt::CurrentTime
are thread-safe (meaning they may be called concurrently from multiple threads), including those that set and retrieve the callback function. In addition, user-supplied callback functions must be thread-safe.
Usage
This section illustrates intended use of this component.
Example 1: Repeatable Tests Involving Current Time
Suppose we are writing an application which involves dealing with the current time (for example, a clock displaying it). In order to test the application, we would like to be able to control the time it sees. We can use bdlt::CurrentTime
for this purpose.
First, we create a sample application. For this example, we simply have it retrieve the current time in several formats:
{
}
Definition bdlt_datetime.h:331
Definition bsls_timeinterval.h:301
static bsls::TimeInterval now()
Definition bdlt_currenttime.h:290
static Datetime local()
Definition bdlt_currenttime.h:280
static Datetime utc()
Definition bdlt_currenttime.h:296
Then, we create a method to test whether the application is producing the expected results:
{
sampleApplication(&local, &utc, &now);
return expectedLocal == local &&
expectedUtc == utc &&
expectedNow == now;
}
Next, we create a class allowing us to set the current time which will be seen by the application:
class TestCurrentTimeGuard {
private:
public:
TestCurrentTimeGuard();
~TestCurrentTimeGuard();
};
TestCurrentTimeGuard::TestCurrentTimeGuard()
: d_prev(
bdlt::CurrentTime::setCurrentTimeCallback(time))
{
}
TestCurrentTimeGuard::~TestCurrentTimeGuard()
{
}
{
return s_time;
}
Definition bbldc_basicisma30360.h:112
bsls::TimeInterval(* CurrentTimeCallback)()
Definition bdlt_currenttime.h:210
static CurrentTimeCallback setCurrentTimeCallback(CurrentTimeCallback callback)
Definition bdlt_currenttime.h:313
Finally, we write a method that tests that our application is functioning correctly:
void testApplication()
{
TestCurrentTimeGuard tct;
sampleApplication(&local, &utc, &now);
TestCurrentTimeGuard::s_time += 1E6;
now += 1E6;
assert(checkApplication(local, utc, now));
}
Datetime & addSeconds(bsls::Types::Int64 seconds)
Definition bdlt_datetime.h:2024
static const Datetime & epoch()
Definition bdlt_epochutil.h:375
static bsls::TimeInterval convertToTimeInterval(const Datetime &datetime)
Definition bdlt_epochutil.h:513