From 8d030f738675c72dcd7949b76a197bbfb892791b Mon Sep 17 00:00:00 2001 From: milarin Date: Thu, 19 Jan 2023 10:16:43 +0100 Subject: [PATCH] telegram message send offset introduced --- envvars.go | 1 + telegram.go | 5 +---- utils.go | 15 +++++++++++++++ 3 files changed, 17 insertions(+), 4 deletions(-) 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)) + } +}