Time Shield Library
C++ library for working with time
Toggle main menu visibility
Loading...
Searching...
No Matches
ntp_time_service_example.cpp
Go to the documentation of this file.
1
3
4
#include <cstdint>
5
#include <iostream>
6
7
#include <
time_shield/config.hpp
>
8
9
#if TIME_SHIELD_ENABLE_NTP_CLIENT
10
# include <
time_shield/initialization.hpp
>
11
# include <
time_shield/ntp_time_service.hpp
>
12
13
int
main
() {
14
// Initialize library internals before using time-related helpers.
15
time_shield::init
();
16
17
// Start the background NTP service with a simple polling interval.
18
if
(!
time_shield::ntp::init
(30000)) {
19
std::cerr <<
"Failed to start NTP time service."
<< std::endl;
20
return
1;
21
}
22
23
// Read corrected UTC time and the current measured offset.
24
const
int64_t utc_ms =
time_shield::ntp::utc_time_ms
();
25
const
int64_t offset_us =
time_shield::ntp::offset_us
();
26
const
bool
is_ok =
time_shield::ntp::last_measure_ok
();
27
28
std::cout <<
"UTC time (ms): "
<< utc_ms << std::endl;
29
std::cout <<
"Offset (us): "
<< offset_us << std::endl;
30
std::cout <<
"Last measurement ok: "
<< (is_ok ?
"true"
:
"false"
) << std::endl;
31
32
// Stop the service before exiting the application.
33
time_shield::ntp::shutdown
();
34
return
0;
35
}
36
37
#else
38
39
int
main
() {
40
std::cout <<
"NTP time service is disabled in this build."
<< std::endl;
41
return
0;
42
}
43
44
#endif
config.hpp
Configuration macros for the library.
time_shield::init
void init()
Initializes the Time Shield library.
Definition
initialization.hpp:23
time_shield::ntp::last_measure_ok
bool last_measure_ok() noexcept
Return whether last measurement updated the offset.
Definition
ntp_time_service.hpp:829
time_shield::ntp::offset_us
int64_t offset_us() noexcept
Return last estimated offset in microseconds.
Definition
ntp_time_service.hpp:801
time_shield::ntp::shutdown
void shutdown()
Stop NTP time service.
Definition
ntp_time_service.hpp:794
time_shield::ntp::utc_time_ms
int64_t utc_time_ms() noexcept
Return current UTC time in milliseconds based on offset.
Definition
ntp_time_service.hpp:815
time_shield::ntp::init
bool init(std::chrono::milliseconds interval=std::chrono::seconds(30), bool measure_immediately=true)
Initialize NTP time service and start background measurements.
Definition
ntp_time_service.hpp:777
initialization.hpp
Initialization helpers for the Time Shield library.
ntp_time_service.hpp
main
int main()
Definition
ntp_time_service_example.cpp:13
examples
ntp_time_service_example.cpp
Generated by
1.17.0