The mechanism isn’t well understood, but we are getting a pretty good idea of the brain structures involved. The cerebellum appears to be the organ that measures discreet time intervals, in stopwatch fashion. The basal ganglia seem to pick up on and anticipate regular beats (when beats become irregular, the cerebellum takes over).
The assumption is that the brain must have some regular internal rhythm—a pacemaker—against which it measures external signals, and a couple of possibilities have been hypothesized. One is a brain stem structure called the inferior olive. It has been found to generate an oscillating electronic coupling that, through feedback from connecting structures, could serve this function. This seems to apply more to the perception of discreet intervals.
In the case of regular beat measurement, many studies have identified a loop between the striatum, the thalamus, and the cortex that involves the dopamine cycle. This loop is monitored by the basal ganglia and correlated to short-term memory.
If you feel up to the challenge, there’s an in-depth article in Nature that presents the neuroscience (you’ll need institutional access to read this, but your library may have such access)