我如何得到通知我的Cocoa应用程序中的系统时间更改? [英] How can I get notified of a system time change in my Cocoa application?

查看:171
本文介绍了我如何得到通知我的Cocoa应用程序中的系统时间更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Cocoa应用程序记录事件的日期戳。我需要知道什么时候系统时间被重置和多少,但我似乎没有罚款通知任何地方告诉我这样的事情发生了。此更改可能发生,因为NTP重置时钟或因为用户重置(例如从系统偏好设置)。

I have a Cocoa application that records datestamps on events. I need to know when the system time is reset and by how much, but I can't seem to fine a notification anywhere that tells me such a thing has happened. This change could happen because NTP reset the clock or because the user reset (e.g. from System Preferences). It would be great if there was just a NSNotification I could register to receive, but I'm open to any suggestions.

推荐答案

如果只有一个NSNotification我可以注册接收, Apple在Snow Leopard(10.6)中的 NSSystemClockDidChangeNotification 中添加了NSDate的一部分。似乎没有办法在Leopard(10.5)或更早版本。根据 Apple NSDate文档

Apple added in NSSystemClockDidChangeNotification, part of NSDate, in Snow Leopard (10.6). There doesn't appear to be a way to do it in Leopard (10.5) or earlier. Per the Apple NSDate docs:


每当系统时钟更改时发布。这可以通过调用settimeofday()或用户更改日期和时间首选项面板中的值来启动。通知对象为空。此通知不包含userInfo字典。

Posted whenever the system clock is changed. This can be initiated by a call to settimeofday() or the user changing values in the Date and Time Preference panel. The notification object is null. This notification does not contain a userInfo dictionary.

这似乎不会告诉你多少时间已更改。你可以通过定期(例如,在NSTimer中每5秒钟)捕获[NSDate date]的系统时间,将其保存到一个变量中,然后在NSSystemClockDidChangeNotification触发后,捕获新的日期,并使用NSDate的 timeIntervalSinceDate:方法获得差异。

This doesn't appear to tell you "how much" time has changed. You could possibly calculate that by periodically (say, every 5 seconds in a NSTimer) capturing the system time with [NSDate date], saving it into a variable, and then after NSSystemClockDidChangeNotification fires, grab the new date and compare the two together using NSDate's timeIntervalSinceDate: method to get the difference.

不是毫秒甚至第二精确,但很接近。

Not millisecond or even second accurate, but pretty close.

EDIT:请参阅这篇文章。您可以使用 UpTime() C命令获取CPU tics中的系统正常运行时间(稍后您可以将其转换为秒)。你可以使用它来估计多少时间已经改变(假设没有系统重新启动或睡眠)。即使系统时钟由用户或网络时间协议更改,这项工作仍然奏效。

See this post. You could possibly use the UpTime() C command to grab the system uptime in CPU tics (which you can later convert to seconds). You could use this to figure out by how much time has changed (assuming no system restart or sleep). This works even if the system clock is changed by the user or network time protocol.

这篇关于我如何得到通知我的Cocoa应用程序中的系统时间更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆