diff --git a/envvars.go b/envvars.go index dece52c..133fcb1 100644 --- a/envvars.go +++ b/envvars.go @@ -22,6 +22,7 @@ var ( TelegramOrganizeMessagePattern = template.Must(template.New("TELEGRAM_ORGANIZE_MESSAGE_PATTERN").Parse(TelegramOrganizeMessagePatternStr)) TelegramOrganizeMessageSendCondition = envvars.ObjectSlice("TELEGRAM_ORGANIZE_MESSAGE_SEND_CONDITION", ",", []SendCondition{SendConditionAlways}, SendConditionFromString) TelegramOrganizeMessageSendInterval = envvars.Duration("TELEGRAM_ORGANIZE_MESSAGE_SEND_INTERVAL", 0) + TelegramOrganizeMessageSendOffset = envvars.Duration("TELEGRAM_ORGANIZE_MESSAGE_SEND_OFFSET", 0) Uid = envvars.Object("UID", 1000, func(s string) (int, error) { if uid, err := strconv.Atoi(s); err == nil { diff --git a/telegram.go b/telegram.go index 9640f51..e77f7c2 100644 --- a/telegram.go +++ b/telegram.go @@ -3,7 +3,6 @@ package main import ( "context" "strings" - "time" "git.milar.in/milarin/adverr" "git.milar.in/milarin/anilist" @@ -33,9 +32,7 @@ func SendMessagePeriodically() { var messagesPerInterval <-chan []model.AnimeEpisode if TelegramOrganizeMessageSendInterval > 0 { - lastCycle := time.Now().Truncate(TelegramOrganizeMessageSendInterval) - nextCycle := lastCycle.Add(TelegramOrganizeMessageSendInterval) - time.Sleep(time.Until(nextCycle)) + WaitForNextTelegramSendCycle() sendAllQueuedAnimeEpisodes() grouperFunc := func(current []model.AnimeEpisode, value model.AnimeEpisode) []model.AnimeEpisode { diff --git a/utils.go b/utils.go index 8f254ef..8c8778e 100644 --- a/utils.go +++ b/utils.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "os" + "time" "git.milar.in/milarin/channel" "git.milar.in/milarin/gmath" @@ -48,3 +49,17 @@ func PrintFileHandle(fh *FileHandle) { panic(err) // TODO error handling } } + +func WaitForNextTelegramSendCycle() { + now := time.Now() + _, offset := now.Zone() + offsetDuration := time.Duration(offset) * time.Second + lastCycle := now.Truncate(TelegramOrganizeMessageSendInterval).Add(-offsetDuration).Add(TelegramOrganizeMessageSendOffset) + + if durationUntilLastCycle := time.Until(lastCycle); durationUntilLastCycle > 0 { + time.Sleep(durationUntilLastCycle) + } else { + nextCycle := lastCycle.Add(TelegramOrganizeMessageSendInterval) + time.Sleep(time.Until(nextCycle)) + } +}