How can I get notified of a system time change in my Cocoa application?

后端 未结 4 1976
一向
一向 2021-01-04 10:49

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

4条回答
  •  一个人的身影
    2021-01-04 11:13

    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:

    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.

    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: 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.

提交回复
热议问题