@@ -23,25 +23,42 @@ class StatusMenuController: NSObject {
2323 formatter. timeZone = TimeZone ( identifier: " Etc/UTC " )
2424 formatter. dateFormat = " HH:mm zzz "
2525
26- // Set up a timer running every 0.03 seconds that gets the current time and formats it for the menu bar.
26+ let calendar = Calendar . current
27+
28+ // Set up a timer running every 0.01 seconds that gets the current time and formats it, if needed, for the menu bar.
2729 // (Most other utilities like this one run a timer like this every 1.00 seconds, which is bad and wrong.)
28- Timer . scheduledTimer ( withTimeInterval: 0.03 , repeats: true ) { _ in
30+ Timer . scheduledTimer ( withTimeInterval: 0.01 , repeats: true ) { _ in
2931 let now = Date ( timeIntervalSinceNow: 0 )
3032
31- let dateString = formatter. string ( from: now)
33+ // Check the current millisecond to see if we actually need to update the time string.
34+ let centisecond = calendar. component ( . nanosecond, from: now) / 10000000
35+ switch centisecond {
36+ case 0 :
37+ // We've got a second on the second (approximately). We need to update the time.
38+ // Format the current time into a human-readable string and set the title.
39+ let timeString = formatter. string ( from: now)
40+ self . statusItem. attributedTitle = self . formatTimeString ( string: timeString)
41+ default :
42+ // We don't need to format the time, so...do nothing.
43+ break
44+ }
3245
33- // To style this with monospaced digits (so other menu bar items don't wobble side-to-side with variable digit widths), we need to set up a NSMutableAttributedString. Joy!
34- let attributedString = NSMutableAttributedString ( string: dateString)
35- // Set the range to cover the entire character range.
36- let range = NSRange ( location: 0 , length: dateString. count)
37- // And finally, apply the monospaced digit system font.
38- attributedString. addAttribute ( . font, value: NSFont . monospacedDigitSystemFont ( ofSize: 14 , weight: . regular) , range: range)
3946
40- // And it's done! Set the title for the menu bar item.
41- self . statusItem. attributedTitle = attributedString
4247 }
4348 }
4449
50+ private func formatTimeString( string: String ) -> NSMutableAttributedString {
51+ // Set up an attributed string.
52+ let attributedString = NSMutableAttributedString ( string: string)
53+ // Set the range to cover the entire character range.
54+ let range = NSRange ( location: 0 , length: string. count)
55+ // Apply the monospaced digit system font.
56+ attributedString. addAttribute ( . font, value: NSFont . monospacedDigitSystemFont ( ofSize: 14 , weight: . regular) , range: range)
57+
58+ // We're done here; return the attributed string.
59+ return attributedString
60+ }
61+
4562 @IBAction func quitClicked( _ sender: Any ) {
4663 // Quit the application.
4764 NSApplication . shared. terminate ( self )
0 commit comments