// Copyright 2021 Kentaro Hibino. All rights reserved.
// Use of this source code is governed by a MIT license
// that can be found in the LICENSE file.

package asynq

import (
	
	

	
	
)

// A janitor is responsible for deleting expired completed tasks from the specified
// queues. It periodically checks for any expired tasks in the completed set, and
// deletes them.
type janitor struct {
	logger *log.Logger
	broker base.Broker

	// channel to communicate back to the long running "janitor" goroutine.
	done chan struct{}

	// list of queue names to check.
	queues []string

	// average interval between checks.
	avgInterval time.Duration
}

type janitorParams struct {
	logger   *log.Logger
	broker   base.Broker
	queues   []string
	interval time.Duration
}

func newJanitor( janitorParams) *janitor {
	return &janitor{
		logger:      .logger,
		broker:      .broker,
		done:        make(chan struct{}),
		queues:      .queues,
		avgInterval: .interval,
	}
}

func ( *janitor) () {
	.logger.Debug("Janitor shutting down...")
	// Signal the janitor goroutine to stop.
	.done <- struct{}{}
}

// start starts the "janitor" goroutine.
func ( *janitor) ( *sync.WaitGroup) {
	.Add(1)
	 := time.NewTimer(.avgInterval) // randomize this interval with margin of 1s
	go func() {
		defer .Done()
		for {
			select {
			case <-.done:
				.logger.Debug("Janitor done")
				return
			case <-.C:
				.exec()
				.Reset(.avgInterval)
			}
		}
	}()
}

func ( *janitor) () {
	for ,  := range .queues {
		if  := .broker.DeleteExpiredCompletedTasks();  != nil {
			.logger.Errorf("Failed to delete expired completed tasks from queue %q: %v",
				, )
		}
	}
}