Skip to content

Commit

Permalink
Merge pull request #17 from thiagokokada/reduce-cpu-usage
Browse files Browse the repository at this point in the history
Reduce cpu usage
  • Loading branch information
thiagokokada authored Jan 16, 2024
2 parents ad2e112 + b7d01da commit d541fba
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 9 deletions.
16 changes: 9 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,15 @@ func sendNotification(
text string,
notificationSound bool,
) notify.Notification {
if notificationSound {
playSendNotificationSound()
}

notification, err := notifier.CreateNotification(title, text)
if err != nil {
log.Printf("Error while sending notification: %v\n", err)
return nil
}
if notificationSound {
playSendNotificationSound()
}
return notification
}

Expand All @@ -78,15 +79,16 @@ func cancelNotificationAfter(
if notification == nil {
return
}

time.Sleep(after)

if notificationSound {
playCancelNotificationSound()
}

err := notification.Cancel()
if err != nil {
fmt.Printf("Error while cancelling notification: %v\n", err)
}
if notificationSound {
playCancelNotificationSound()
}
}

func twentyTwentyTwenty(
Expand Down
14 changes: 12 additions & 2 deletions notification_sound.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ import (

const notificationSoundEnabled bool = true

// Maximum lag, good enough for this use case and will use lower CPU, but need
// to compesate the lag with time.Sleep() to not feel "strange" (e.g.: "floaty"
// notifications because the sound comes too late).
// About as good we can get of CPU usage for now, until this issue is fixed:
// https://github.com/gopxl/beep/issues/137.
const lag time.Duration = time.Second

var (
buffer1 *beep.Buffer
buffer2 *beep.Buffer
Expand All @@ -31,6 +38,8 @@ func playSendNotificationSound() {
beep.Callback(func() { done <- true }),
)
<-done
// compesate the lag
time.Sleep(lag)
}

func playCancelNotificationSound() {
Expand All @@ -40,6 +49,8 @@ func playCancelNotificationSound() {
beep.Callback(func() { done <- true }),
)
<-done
// compesate the lag
time.Sleep(lag)
}

func initNotification() error {
Expand Down Expand Up @@ -71,8 +82,7 @@ func initNotification() error {
return fmt.Errorf("notification 2 sound failed: %w", err)
}

// 1s/8 = 125ms of maximum lag, good enough for this use case
speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/8))
speaker.Init(format.SampleRate, format.SampleRate.N(lag))

return nil
}

0 comments on commit d541fba

Please sign in to comment.