scheduler

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 3, 2026 License: Apache-2.0, BSD-3-Clause, MIT Imports: 10 Imported by: 0

Documentation

Overview

Package scheduler provides admin panel integration Per AI.md PART 19: Admin panel must show actual scheduler runtime state

Package scheduler provides a built-in task scheduler per AI.md PART 19 The scheduler is ALWAYS RUNNING - there is no enable/disable option. All scheduled tasks are managed internally, never via external cron/schedulers.

Index

Constants

View Source
const (
	DefaultMaxRetries = 3
	DefaultRetryDelay = 5 * time.Minute
)

Default retry policy values per AI.md PART 19

Variables

This section is empty.

Functions

This section is empty.

Types

type AdminAdapter

type AdminAdapter struct {
	// contains filtered or unexported fields
}

AdminAdapter wraps Scheduler to implement admin.SchedulerManager interface Per AI.md PART 19: Admin panel integration with scheduler

func NewAdminAdapter

func NewAdminAdapter(s *Scheduler) *AdminAdapter

NewAdminAdapter creates an adapter for admin panel integration

func (*AdminAdapter) Disable

func (a *AdminAdapter) Disable(id string) error

Disable disables a task

func (*AdminAdapter) Enable

func (a *AdminAdapter) Enable(id string) error

Enable enables a task

func (*AdminAdapter) GetTask

func (a *AdminAdapter) GetTask(id string) (*admin.SchedulerTaskInfo, error)

GetTask returns a specific task by ID

func (*AdminAdapter) GetTasks

func (a *AdminAdapter) GetTasks() []*admin.SchedulerTaskInfo

GetTasks returns all registered tasks with runtime state

func (*AdminAdapter) IsRunning

func (a *AdminAdapter) IsRunning() bool

IsRunning returns whether the scheduler is running

func (*AdminAdapter) RunNow

func (a *AdminAdapter) RunNow(id string) error

RunNow triggers immediate execution of a task

type ClusterScheduler

type ClusterScheduler struct {
	*Scheduler
	// contains filtered or unexported fields
}

ClusterScheduler extends Scheduler with cluster-safe distributed locking Per AI.md PART 9: Database-backed scheduler with cluster-safe locking

func NewClusterScheduler

func NewClusterScheduler(db *sql.DB, nodeID string) (*ClusterScheduler, error)

NewClusterScheduler creates a new cluster-aware scheduler

func (*ClusterScheduler) AcquireLock

func (cs *ClusterScheduler) AcquireLock(ctx context.Context, taskName string) (bool, error)

AcquireLock attempts to acquire a distributed lock for a task

func (*ClusterScheduler) CleanupOldExecutions

func (cs *ClusterScheduler) CleanupOldExecutions(ctx context.Context, retention time.Duration) (int64, error)

CleanupOldExecutions removes old execution records

func (*ClusterScheduler) CompleteExecution

func (cs *ClusterScheduler) CompleteExecution(ctx context.Context, executionID int64, err error) error

CompleteExecution marks an execution as completed

func (*ClusterScheduler) GetExecutionHistory

func (cs *ClusterScheduler) GetExecutionHistory(ctx context.Context, taskName string, limit int) ([]*TaskExecution, error)

GetExecutionHistory returns recent executions for a task

func (*ClusterScheduler) GetMissedJobs

func (cs *ClusterScheduler) GetMissedJobs(ctx context.Context) ([]*ClusterTaskState, error)

GetMissedJobs returns tasks that were missed while the cluster was down Per AI.md PART 9: Catchup for missed jobs

func (*ClusterScheduler) GetTaskState

func (cs *ClusterScheduler) GetTaskState(ctx context.Context, taskName string) (*ClusterTaskState, error)

GetTaskState gets the shared task state

func (*ClusterScheduler) Hostname

func (cs *ClusterScheduler) Hostname() string

Hostname returns the current node's hostname

func (*ClusterScheduler) NodeID

func (cs *ClusterScheduler) NodeID() string

NodeID returns the current node's ID

func (*ClusterScheduler) RecordExecution

func (cs *ClusterScheduler) RecordExecution(ctx context.Context, taskName string, scheduledAt time.Time) (int64, error)

RecordExecution records a task execution

func (*ClusterScheduler) ReleaseLock

func (cs *ClusterScheduler) ReleaseLock(ctx context.Context, taskName string) error

ReleaseLock releases a distributed lock

func (*ClusterScheduler) RunWithLock

func (cs *ClusterScheduler) RunWithLock(ctx context.Context, task *Task) error

RunWithLock runs a task with distributed locking

func (*ClusterScheduler) SetLockTTL

func (cs *ClusterScheduler) SetLockTTL(ttl time.Duration)

SetLockTTL sets the lock time-to-live

func (*ClusterScheduler) StartCluster

func (cs *ClusterScheduler) StartCluster()

StartCluster starts the cluster-aware scheduler

func (*ClusterScheduler) UpdateTaskState

func (cs *ClusterScheduler) UpdateTaskState(ctx context.Context, taskName string, lastRun, nextRun time.Time) error

UpdateTaskState updates the shared task state

type ClusterTaskState

type ClusterTaskState struct {
	TaskName     string    `json:"task_name"`
	LastRun      time.Time `json:"last_run"`
	NextRun      time.Time `json:"next_run"`
	LastNodeID   string    `json:"last_node_id"`
	LastHostname string    `json:"last_hostname"`
	UpdatedAt    time.Time `json:"updated_at"`
}

ClusterTaskState represents shared task state across the cluster

type NotifyFunc

type NotifyFunc func(notification *TaskFailureNotification)

NotifyFunc is a callback function for task failure notifications Per AI.md PART 19: Failed tasks trigger notifications (if configured)

type Scheduler

type Scheduler struct {
	// contains filtered or unexported fields
}

Scheduler manages periodic tasks per AI.md PART 19 The scheduler is ALWAYS RUNNING - no enable/disable option exists

func New

func New(db *sql.DB, nodeID string) *Scheduler

New creates a new scheduler Per AI.md PART 19: Scheduler is ALWAYS RUNNING

func (*Scheduler) Disable

func (s *Scheduler) Disable(id TaskID) error

Disable disables a task

func (*Scheduler) Enable

func (s *Scheduler) Enable(id TaskID) error

Enable enables a task

func (*Scheduler) GetTask

func (s *Scheduler) GetTask(id TaskID) (*TaskInfo, error)

GetTask returns a specific task

func (*Scheduler) GetTasks

func (s *Scheduler) GetTasks() []*TaskInfo

GetTasks returns all registered tasks

func (*Scheduler) IsRunning

func (s *Scheduler) IsRunning() bool

IsRunning returns whether the scheduler is running

func (*Scheduler) Register

func (s *Scheduler) Register(task *Task) error

Register adds a task to the scheduler

func (*Scheduler) RegisterBuiltinTasks

func (s *Scheduler) RegisterBuiltinTasks(handlers *TaskHandlers)

RegisterBuiltinTasks registers all required tasks per AI.md PART 19

func (*Scheduler) RunNow

func (s *Scheduler) RunNow(id TaskID) error

RunNow runs a task immediately

func (*Scheduler) SetCatchUpWindow

func (s *Scheduler) SetCatchUpWindow(d time.Duration)

SetCatchUpWindow sets the catch-up window for missed tasks

func (*Scheduler) SetNotifyFunc

func (s *Scheduler) SetNotifyFunc(fn NotifyFunc)

SetNotifyFunc sets the callback function for task failure notifications Per AI.md PART 19: Failed tasks trigger notifications (if configured)

func (*Scheduler) SetTimezone

func (s *Scheduler) SetTimezone(tz string) error

SetTimezone sets the timezone for scheduled tasks

func (*Scheduler) Start

func (s *Scheduler) Start()

Start starts the scheduler Per AI.md PART 19: Scheduler is ALWAYS RUNNING

func (*Scheduler) Stop

func (s *Scheduler) Stop()

Stop stops the scheduler

type Task

type Task struct {
	ID          TaskID
	Name        string
	Description string
	Schedule    string   // Cron expression or @every interval
	TaskType    TaskType // Global or Local
	Run         func(ctx context.Context) error
	Skippable   bool // Can admin disable this task?
	RunOnStart  bool // Run immediately on scheduler start?

	// Retry policy per AI.md PART 19
	// Default: max_retries=3, retry_delay=5m, backoff=exponential (5m, 10m, 20m)
	MaxRetries int           // Maximum retry attempts (default: 3)
	RetryDelay time.Duration // Base delay between retries (default: 5m)

	// Runtime state (persisted to database)
	LastRun    time.Time
	LastStatus TaskStatus
	LastError  string
	NextRun    time.Time
	RunCount   int64
	FailCount  int64
	Enabled    bool

	// Retry state
	RetryCount int       // Current retry attempt (0 = first run)
	NextRetry  time.Time // Scheduled retry time (if retrying)

	// Cluster locking
	LockedBy string
	LockedAt time.Time
}

Task represents a scheduled task per AI.md PART 19

type TaskExecution

type TaskExecution struct {
	ID          int64     `json:"id"`
	TaskName    string    `json:"task_name"`
	NodeID      string    `json:"node_id"`
	Hostname    string    `json:"hostname"`
	Status      string    `json:"status"` // running, completed, failed
	StartedAt   time.Time `json:"started_at"`
	CompletedAt time.Time `json:"completed_at,omitempty"`
	Error       string    `json:"error,omitempty"`
	ScheduledAt time.Time `json:"scheduled_at"`
}

TaskExecution represents a task execution record in the database

type TaskFailureNotification

type TaskFailureNotification struct {
	TaskID    string
	TaskName  string
	Error     string
	Attempts  int
	LastRun   time.Time
	FailCount int64
}

TaskFailureNotification contains details about a failed task Per AI.md PART 19: Failed tasks trigger notifications (if configured)

type TaskHandlers

type TaskHandlers struct {
	SSLRenewal       func(ctx context.Context) error
	GeoIPUpdate      func(ctx context.Context) error
	BlocklistUpdate  func(ctx context.Context) error
	CVEUpdate        func(ctx context.Context) error
	SessionCleanup   func(ctx context.Context) error
	TokenCleanup     func(ctx context.Context) error
	LogRotation      func(ctx context.Context) error
	BackupDaily      func(ctx context.Context) error
	BackupHourly     func(ctx context.Context) error
	HealthcheckSelf  func(ctx context.Context) error
	TorHealth        func(ctx context.Context) error
	ClusterHeartbeat func(ctx context.Context) error
}

TaskHandlers holds handler functions for built-in tasks

type TaskID

type TaskID string

TaskID represents a unique task identifier

const (
	TaskSSLRenewal       TaskID = "ssl.renewal"
	TaskGeoIPUpdate      TaskID = "geoip.update"
	TaskBlocklistUpdate  TaskID = "blocklist.update"
	TaskCVEUpdate        TaskID = "cve.update"
	TaskSessionCleanup   TaskID = "session.cleanup"
	TaskTokenCleanup     TaskID = "token.cleanup"
	TaskLogRotation      TaskID = "log.rotation"
	TaskBackupDaily      TaskID = "backup_daily"
	TaskBackupHourly     TaskID = "backup_hourly"
	TaskHealthcheckSelf  TaskID = "healthcheck.self"
	TaskTorHealth        TaskID = "tor.health"
	TaskClusterHeartbeat TaskID = "cluster.heartbeat"
)

Built-in task IDs per AI.md PART 19

type TaskInfo

type TaskInfo struct {
	ID          string    `json:"id"`
	Name        string    `json:"name"`
	Description string    `json:"description"`
	Schedule    string    `json:"schedule"`
	TaskType    string    `json:"task_type"`
	LastRun     time.Time `json:"last_run"`
	LastStatus  string    `json:"last_status"`
	LastError   string    `json:"last_error,omitempty"`
	NextRun     time.Time `json:"next_run"`
	RunCount    int64     `json:"run_count"`
	FailCount   int64     `json:"fail_count"`
	Enabled     bool      `json:"enabled"`
	Skippable   bool      `json:"skippable"`

	// Retry state per AI.md PART 19
	RetryCount int       `json:"retry_count"`
	NextRetry  time.Time `json:"next_retry,omitempty"`
	MaxRetries int       `json:"max_retries"`
}

TaskInfo represents task information for API/UI

type TaskLock

type TaskLock struct {
	TaskName   string    `json:"task_name"`
	NodeID     string    `json:"node_id"`
	Hostname   string    `json:"hostname"`
	AcquiredAt time.Time `json:"acquired_at"`
	ExpiresAt  time.Time `json:"expires_at"`
}

TaskLock represents a distributed lock for a task

type TaskState

type TaskState struct {
	TaskID     string
	TaskName   string
	Schedule   string
	LastRun    time.Time
	LastStatus string
	LastError  string
	NextRun    time.Time
	RunCount   int64
	FailCount  int64
	Enabled    bool
	LockedBy   string
	LockedAt   time.Time
}

TaskState represents persisted task state in database

type TaskStatus

type TaskStatus string

TaskStatus represents task execution status

const (
	StatusSuccess  TaskStatus = "success"
	StatusFailed   TaskStatus = "failed"
	StatusSkipped  TaskStatus = "skipped"
	StatusRunning  TaskStatus = "running"
	StatusRetrying TaskStatus = "retrying"
)

type TaskType

type TaskType string

TaskType determines how tasks run in cluster mode

const (
	// TaskTypeGlobal runs on ONE node only (leader election)
	TaskTypeGlobal TaskType = "global"
	// TaskTypeLocal runs on EVERY node
	TaskTypeLocal TaskType = "local"
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL