Linux中如何检测系统时间的变化?
当时间服务器更新系统时间或由于夏令时更改时,有没有办法收到通知?我正在执行 API/系统调用或同等功能。
我努力的一部分是在不使用 SQL 的情况下将类似于 SQL NOW() 的值的生成优化到小时粒度。
Is there a way to get notified when there is update to the system time from a time-server or due to DST change? I am after an API/system call or equivalent.
It is part of my effort to optimise generating a value for something similar to SQL NOW() to an hour granularity, without using SQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 timerfd_create(2) 创建计时器,然后设置时使用
TFD_TIMER_CANCEL_ON_SET
选项进行标记。将其设置为未来一个难以置信的时间,然后阻止它(使用轮询/选择等) - 如果系统时间发生变化,那么计时器将被取消,您可以检测到这一点。(这是systemd 是如何做到的 )
例如:
You can use timerfd_create(2) to create a timer, then mark it with the
TFD_TIMER_CANCEL_ON_SET
option when setting it. Set it for an implausible time in the future and then block on it (with poll/select etc.) - if the system time changes then the timer will be cancelled, which you can detect.(this is how systemd does it)
e.g.:
我不知道是否有办法通知系统时间的更改,但是
系统时间存储为UTC,因此永远不会因DST更改而通知更改。
如果我没记错的话,NTP守护进程通常通过改变时钟速度来调整时钟,同样没有通知通知。
如果我没记错的话,NTP
因此,只有在发生不常见的操作之后,您才会收到通知。
I don't know if there is a way to be notified of a change in the system time, but
The system time is stored as UTC, so there is never a change due to DST change to be notified.
If my memory is correct, NTP deamon usually adjust the clock by changing its speed, again no change to be notified.
So the only times where you would be notified is after an uncommon manipulation.
最新 Linux 系统上的
clock_gettime
速度快得令人难以置信,而且通常也非常精确;您可以使用clock_getres
找出精度。但对于小时级别的时间戳,gettimeofday
可能更方便,因为它可以为您进行时区调整。只需调用适当的系统调用,并在每次需要时间戳时将其划分为小时; NTP 的所有其他时间调整或其他已经为您完成的时间调整。
clock_gettime
on most recent Linux systems is incredibly fast, and usually pretty amazingly precise as well; you can find out the precision usingclock_getres
. But for hour level timestamps,gettimeofday
might be more convenient since it can do the timezone adjustment for you.Simply call the appropriate system call and do the division into hours each time you need a timestamp; all the other time adjustments from NTP or whatever will already have been done for you.