Timers
CPUs have a hardware based timer circuit which can be configured to work like a stopwatch. Whenever the timer reaches the configured value, it generates an interrupt to the CPU.
CPUs don't have concept of time. They only have a concept of clock cycles. Knowing the frequency of the clock cycles, we convert this into time.
These are two different things and also have different values.
For example, CPU cycle frequency can have an impact due to thermal throttling. But the timer frequency is always constant.

CPU can be configured to provide two types of timers:
- One-shot timer: It generates an interrupt only once when the timer reaches the configured value. The user must reconfigure the timer again to generate another interrupt.
- Periodic timer: Timer is configured once, and it generates interrupts at that interval.
CPUs have two different types of circuits.
- Timer - which fires an interrupt when the timer reaches the configured value.
- Counter - which counts the number of events that happen in the CPU.
In the latest CPUs, the timer uses the counter circuit itself. For every increment, the circuit updates the value in the counter register. Then the same value flows to a comparator circuit in the timer. When the counter value matches the configured value in timer, it generates an interrupt.
How counter knows the time has lapsed?
Counter is a register in the CPU which can be read by any process using a specific instruction. The value in this register is incremented by every clock cycle coming from the external signal source
The counter only counts number of signals received. And the frequency of the generated signal is used to convert this into time and vice versa.
During boot, this information is fetched using a CPU instruction and stored in the kernel.
Context Switching with Timers
Kernel uses this feature of CPU to implement [context switching](computers/context-switching#context-switch-by-os - software-switch).
Counters for maintaining time
The kernel fetches actual time using NTP servers only at regular intervals. But in between, it uses the same CPU counter to maintain the time.
The CPU has only one counter and timer circuit. Kernel sets the timer to the next least required timer interrupt. If the next timer interrupt is for context switching, then it sets the timer to that value. If the next tier interrupt is for a thread sleeping, it sets that value.