63 lines
1.6 KiB
Go
63 lines
1.6 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"time"
|
|
)
|
|
|
|
// ExchangeRateScheduler handles scheduled fetching of exchange rates
|
|
type ExchangeRateScheduler struct {
|
|
yunAPIClient *YunAPIClient
|
|
interval time.Duration
|
|
stopChan chan struct{}
|
|
}
|
|
|
|
// NewExchangeRateScheduler creates a new ExchangeRateScheduler
|
|
func NewExchangeRateScheduler(yunAPIClient *YunAPIClient, interval time.Duration) *ExchangeRateScheduler {
|
|
return &ExchangeRateScheduler{
|
|
yunAPIClient: yunAPIClient,
|
|
interval: interval,
|
|
stopChan: make(chan struct{}),
|
|
}
|
|
}
|
|
|
|
// Start begins the scheduled fetching of exchange rates
|
|
// It fetches immediately on start, then every interval
|
|
func (s *ExchangeRateScheduler) Start(ctx context.Context) {
|
|
log.Printf("[Scheduler] Starting exchange rate scheduler with interval: %v", s.interval)
|
|
|
|
// Fetch immediately on start
|
|
s.fetchRates()
|
|
|
|
// Create ticker for periodic fetching
|
|
ticker := time.NewTicker(s.interval)
|
|
defer ticker.Stop()
|
|
|
|
for {
|
|
select {
|
|
case <-ticker.C:
|
|
s.fetchRates()
|
|
case <-s.stopChan:
|
|
log.Println("[Scheduler] Exchange rate scheduler stopped")
|
|
return
|
|
case <-ctx.Done():
|
|
log.Println("[Scheduler] Exchange rate scheduler stopped due to context cancellation")
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
// Stop stops the scheduler
|
|
func (s *ExchangeRateScheduler) Stop() {
|
|
close(s.stopChan)
|
|
}
|
|
|
|
// fetchRates calls the YunAPI client to fetch and save rates
|
|
func (s *ExchangeRateScheduler) fetchRates() {
|
|
log.Println("[Scheduler] Triggering exchange rate fetch...")
|
|
if err := s.yunAPIClient.FetchAndSaveRates(); err != nil {
|
|
log.Printf("[Scheduler] Error fetching exchange rates: %v", err)
|
|
}
|
|
}
|