慕斯709654
下面的代码达到了你的目的。您所要做的就是按照下面 main() 函数中显示的方式调用 ScheduleAlarm()。package mainimport ( "strings" "strconv" "fmt" "time")// A struct for representing time.type Time struct { Hh int // Hours. Mm int // Minutes. Ss int // Seconds.}func main() { /* Set the alarm as shown below. Time must be specified in 24 hour clock format. Also, pass the callback to be called after the alarm is triggered. */ alarm := ScheduleAlarm(Time{23, 28, 0}, func() { fmt.Println("alarm received") }) // Do your stuff. for i := 0; i < 10; i++ { fmt.Println(i) time.Sleep(2 * time.Second) } // Don't forget to call the below line whenever you want to block. <-alarm}// Call this function to schedule the alarm. The callback will be called after the alarm is triggered.func ScheduleAlarm(alarmTime Time, callback func() ()) (endRecSignal chan string) { endRecSignal = make(chan string) go func() { timeSplice := strings.Split(time.Now().Format("15:04:05"), ":") hh, _ := strconv.Atoi(timeSplice[0]) mm, _ := strconv.Atoi(timeSplice[1]) ss, _ := strconv.Atoi(timeSplice[2]) startAlarm := GetDiffSeconds(Time{hh, mm, ss}, alarmTime) // Setting alarm. time.AfterFunc(time.Duration(startAlarm) * time.Second, func() { callback() endRecSignal <- "finished recording" close(endRecSignal) }) }() return}func GetDiffSeconds(fromTime, toTime Time) int { fromSec := GetSeconds(fromTime) toSec := GetSeconds(toTime) diff := toSec - fromSec if diff < 0 { return diff + 24 * 60 * 60 } else { return diff }}func GetSeconds(time Time) int { return time.Hh * 60 * 60 + time.Mm * 60 + time.Ss}希望这可以帮助。