chapter nine

9 Time and Time Keeping

 

This chapter covers:

  • how a computer keeps time
  • how operating systems represent timestamps
  • synchronize with the world’s atomic clocks with the Network Time Protocol (NTP)

During this chapter, you’ll be producing an NTP client that can request the current time from the world’s network of public time servers. It’s a fully-functioning client that can be included into your own computer’s boot process to keep it in sync with the world.

Understanding of how time works within computers supports your efforts to build resilient applications. The system’s clock jumps both backwards and forwards in time. Knowing why this happens will allow you to anticipate and prepare for that eventuality.

Your computer also contains multiple physical and virtual clocks. It takes some knowledge to understand the limitations of each and when they’re appropriate. Understanding the limitations of each should foster a healthy skepticism of micro benchmarks and other time-sensitive code.

9.1  Background

9.2  Sources of Time

9.3  Definitions

9.4  Encoding Time

9.4.1  Representing time zones

9.5  clock v0.1.0: Teaching an application how to tell the time

9.6  clock v0.1.1: Formatting timestamps to comply with ISO 8601 and email standards

9.6.1  Refactoring the clock v0.1.0 code to support wider architecture

9.6.2  Formatting the time as a UNIX timestamp or a formatted string according to ISO 8601, RFC 2822, and RFC 3339

9.6.3  Providing a full command-line interface

9.6.4  The full clock v0.1.1 code listing

9.7  clock v0.1.2: Setting the time

9.7.1  Common behavior

9.7.2  Setting the time in operating systems that use libc

9.7.3  Setting the time on MS Windows

9.7.4  clock v0.1.2 Full code listing

9.8  Improving error handling

9.9  clock v0.1.3 Resolving differences between clocks with the Network Time Protocol (NTP)