mirror of
https://github.com/muety/wakapi.git
synced 2023-08-10 21:12:56 +03:00
Add database cleanup functionality.
This commit is contained in:
@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
intervalDays int = 1 // TODO: Make configurable
|
||||
aggregateIntervalDays int = 1 // TODO: Make configurable
|
||||
)
|
||||
|
||||
type AggregationService struct {
|
||||
@ -126,7 +126,7 @@ func generateUserJobs(userId string, lastAggregation time.Time, jobs chan<- *Agg
|
||||
from = time.Date(
|
||||
lastAggregation.Year(),
|
||||
lastAggregation.Month(),
|
||||
lastAggregation.Day()+intervalDays,
|
||||
lastAggregation.Day()+aggregateIntervalDays,
|
||||
0, 0, 0, 0,
|
||||
lastAggregation.Location(),
|
||||
)
|
||||
@ -136,7 +136,7 @@ func generateUserJobs(userId string, lastAggregation time.Time, jobs chan<- *Agg
|
||||
to = time.Date(
|
||||
from.Year(),
|
||||
from.Month(),
|
||||
from.Day()+intervalDays,
|
||||
from.Day()+aggregateIntervalDays,
|
||||
0, 0, 0, 0,
|
||||
from.Location(),
|
||||
)
|
||||
|
@ -1,6 +1,9 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"github.com/jasonlvhit/gocron"
|
||||
"github.com/n1try/wakapi/utils"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
@ -8,7 +11,10 @@ import (
|
||||
gormbulk "github.com/t-tiger/gorm-bulk-insert"
|
||||
)
|
||||
|
||||
const TableHeartbeat = "heartbeat"
|
||||
const (
|
||||
TableHeartbeat = "heartbeat"
|
||||
cleanUpInterval = time.Duration(aggregateIntervalDays) * 2 * 24 * time.Hour
|
||||
)
|
||||
|
||||
type HeartbeatService struct {
|
||||
Config *models.Config
|
||||
@ -55,3 +61,29 @@ func (srv *HeartbeatService) GetFirstUserHeartbeats(userIds []string) ([]*models
|
||||
}
|
||||
return heartbeats, nil
|
||||
}
|
||||
|
||||
func (srv *HeartbeatService) DeleteBefore(t time.Time) error {
|
||||
if err := srv.Db.
|
||||
Where("time <= ?", t).
|
||||
Delete(models.Heartbeat{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (srv *HeartbeatService) CleanUp() error {
|
||||
refTime := utils.StartOfDay().Add(-cleanUpInterval)
|
||||
if err := srv.DeleteBefore(refTime); err != nil {
|
||||
log.Printf("Failed to clean up heartbeats older than %v – %v\n", refTime, err)
|
||||
return err
|
||||
}
|
||||
log.Printf("Successfully cleaned up heartbeats older than %v\n", refTime)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (srv *HeartbeatService) ScheduleCleanUp() {
|
||||
srv.CleanUp()
|
||||
|
||||
gocron.Every(1).Day().At("02:30").Do(srv.CleanUp)
|
||||
<-gocron.Start()
|
||||
}
|
||||
|
Reference in New Issue
Block a user