Skip to content

Create job that perioducally clears the fs #4

@8-prime

Description

@8-prime

Follow this base code to implement

package main

import (
	"bufio"
	"fmt"
	"math/rand"
	"os"
	"sort"
	"time"
)

type Data struct {
	expirations []time.Time
}

func cleanupData() {
	fmt.Println("Running cleanupData...")
	// Add your data cleanup logic here
}

func getNextTimeStamp(data *Data) (time.Time, error) {
	if len(data.expirations) == 0 {
		return time.Time{}, fmt.Errorf("no expirations available")
	}

	sort.Slice(data.expirations, func(i, j int) bool {
		return data.expirations[i].Before(data.expirations[j])
	})

	nextExpiration := data.expirations[0]
	data.expirations = data.expirations[1:] // Remove the used expiration
	return nextExpiration, nil
}

func timestampManager(timestampChan <-chan time.Time, data *Data) {
	var currentTarget time.Time
	timer := time.NewTimer(1 * time.Hour) // Initialize a timer with zero duration

	nextExpiration, err := getNextTimeStamp(data)
	if err == nil {
		timer = time.NewTimer(nextExpiration.Sub(time.Now()))
	}

	for {
		select {
		case newTimestamp := <-timestampChan:
			if currentTarget.IsZero() || newTimestamp.Before(currentTarget) {
				fmt.Println("Updating target timestamp:", newTimestamp)
				if !currentTarget.IsZero() {
					fmt.Println("Adding current target to expirations:", currentTarget)
					data.expirations = append(data.expirations, currentTarget)
				}

				currentTarget = newTimestamp

				timer.Stop()
				timer = time.NewTimer(newTimestamp.Sub(time.Now()))
				fmt.Println("New timer set for:", newTimestamp)
			} else {
				fmt.Println("Received timestamp is later than current target, adding to expirations.")
				data.expirations = append(data.expirations, newTimestamp)
			}
		case <-timer.C:
			cleanupData()
			currentTarget = time.Time{} // Reset current target
			nextExpiration, err := getNextTimeStamp(data)
			if err == nil {
				timer = time.NewTimer(nextExpiration.Sub(time.Now()))
			}
		}
	}
}

func main() {
	data := new(Data)
	timerChan := make(chan time.Time)
	go timestampManager(timerChan, data)
	for {
		reader := bufio.NewReader(os.Stdin)
		text, _ := reader.ReadString('\n')

		randomDuration := time.Duration(1+rand.Intn(30)) * time.Second
		fmt.Printf("New Expiration at: %v\n", randomDuration)
		randomTimestamp := time.Now().Add(randomDuration)
		timerChan <- randomTimestamp
		fmt.Println(text)
	}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions