organizer/utils.go

66 lines
1.5 KiB
Go

package main
import (
"fmt"
"io"
"os"
"time"
"git.milar.in/milarin/channel"
"git.milar.in/milarin/gmath"
)
func InitializeRunner() channel.Runner {
if ThreadCount <= 0 {
return channel.NewUnlimitedRunner()
}
return channel.NewLimitedRunner(ThreadCount)
}
func FormatBytes[T gmath.Integer](bytes T) string {
value := float64(bytes)
if value >= 1000000000000 {
return fmt.Sprintf("%.02fT", value/1000000000000)
} else if value >= 1000000000 {
return fmt.Sprintf("%.02fG", value/1000000000)
} else if value >= 1000000 {
return fmt.Sprintf("%.02fM", value/1000000)
} else if value >= 1000 {
return fmt.Sprintf("%.02fK", value/1000)
} else {
return fmt.Sprintf("%.02fB", value)
}
}
func PrintByteChan(w io.Writer, ch <-chan byte) error {
for b := range ch {
if _, err := w.Write([]byte{b}); err != nil {
return err
}
}
fmt.Fprintln(w)
return nil
}
func PrintFileHandle(fh *FileHandle) {
if err := PrintByteChan(os.Stdout, fh.Chan); err != nil {
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))
}
}