cron

package
v0.0.0-...-8acab51 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2026 License: MIT Imports: 23 Imported by: 0

Documentation

Overview

Package cron provides scheduled task management.

Package cron provides scheduled task management.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CommandResult

type CommandResult struct {
	Command  string `json:"command"`
	ExitCode int    `json:"exit_code"`
	Stdout   string `json:"stdout"`
	Stderr   string `json:"stderr"`
	Duration string `json:"duration"`
}

CommandResult represents the result of a command execution.

type CommandSecurityConfig

type CommandSecurityConfig struct {
	// Enabled controls whether command handler is available
	Enabled bool
	// AllowedCommands is a whitelist of allowed commands (empty = use default)
	AllowedCommands []string
	// RequireAdminRole requires admin role to create command jobs
	RequireAdminRole bool
	// MaxOutputSize limits the output size in bytes
	MaxOutputSize int
}

CommandSecurityConfig holds security configuration for command execution

func DefaultCommandSecurityConfig

func DefaultCommandSecurityConfig() CommandSecurityConfig

DefaultCommandSecurityConfig returns secure defaults

type Config

type Config struct {
	// Enabled indicates if cron is enabled.
	Enabled bool `yaml:"enabled"`
	// MaxConcurrentJobs is the maximum number of concurrent jobs.
	MaxConcurrentJobs int `yaml:"max_concurrent_jobs"`
	// JobTimeoutSeconds is the default job timeout.
	JobTimeoutSeconds int `yaml:"job_timeout_seconds"`
	// ExecutionRetentionHours is how long to keep execution history.
	ExecutionRetentionHours int `yaml:"execution_retention_hours"`
	// MaxExecutionsPerJob is the maximum executions to keep per job.
	MaxExecutionsPerJob int `yaml:"max_executions_per_job"`
}

Config contains cron service configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default cron configuration.

type CreateRequest

type CreateRequest struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Schedule    string                 `json:"schedule" validate:"required"`
	Handler     string                 `json:"handler" validate:"required"`
	Payload     map[string]interface{} `json:"payload"`
}

CreateRequest represents a create job request.

type EventPublisher

type EventPublisher interface {
	Publish(userID string, eventType string, data any)
}

EventPublisher pushes real-time events to connected clients.

type HTTPResult

type HTTPResult struct {
	URL        string `json:"url"`
	Method     string `json:"method"`
	StatusCode int    `json:"status_code"`
	Duration   string `json:"duration"`
}

HTTPResult represents the result of an HTTP request.

type Handler

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

Handler provides HTTP handlers for cron job management.

func NewHandler

func NewHandler(service *Service, logger *zap.Logger) *Handler

NewHandler creates a new cron handler.

func NewLazyHandler

func NewLazyHandler(initFn func() *Service, logger *zap.Logger) *Handler

NewLazyHandler creates a handler that defers Service creation to the first API call. This avoids starting the robfig/cron scheduler goroutine when nobody uses cron.

func (*Handler) Create

func (h *Handler) Create(c echo.Context) error

Create creates a new cron job. @Summary Create cron job @Tags cron @Accept json @Produce json @Param request body CreateRequest true "Create request" @Success 201 {object} Job @Failure 400 {object} map[string]string @Router /api/v1/cron [post]

func (*Handler) Delete

func (h *Handler) Delete(c echo.Context) error

Delete deletes a cron job. @Summary Delete cron job @Tags cron @Param id path string true "Job ID" @Success 200 {object} map[string]string @Failure 404 {object} map[string]string @Router /api/v1/cron/{id} [delete]

func (*Handler) Disable

func (h *Handler) Disable(c echo.Context) error

Disable disables a cron job. @Summary Disable cron job @Tags cron @Param id path string true "Job ID" @Success 200 {object} map[string]string @Failure 404 {object} map[string]string @Router /api/v1/cron/{id}/disable [post]

func (*Handler) Enable

func (h *Handler) Enable(c echo.Context) error

Enable enables a cron job. @Summary Enable cron job @Tags cron @Param id path string true "Job ID" @Success 200 {object} map[string]string @Failure 404 {object} map[string]string @Router /api/v1/cron/{id}/enable [post]

func (*Handler) Get

func (h *Handler) Get(c echo.Context) error

Get returns a cron job by ID. @Summary Get cron job @Tags cron @Produce json @Param id path string true "Job ID" @Success 200 {object} Job @Failure 404 {object} map[string]string @Router /api/v1/cron/{id} [get]

func (*Handler) GetExecutions

func (h *Handler) GetExecutions(c echo.Context) error

GetExecutions returns executions for a cron job. @Summary Get job executions @Tags cron @Produce json @Param id path string true "Job ID" @Param limit query int false "Limit" default(20) @Success 200 {array} JobExecution @Failure 404 {object} map[string]string @Router /api/v1/cron/{id}/executions [get]

func (*Handler) GetExecutionsWrapped

func (h *Handler) GetExecutionsWrapped(c echo.Context) error

GetExecutionsWrapped returns executions in the legacy CLI response shape.

func (*Handler) GetService

func (h *Handler) GetService() *Service

GetService returns the cron service for cleanup purposes.

func (*Handler) List

func (h *Handler) List(c echo.Context) error

List returns all cron jobs. @Summary List cron jobs @Tags cron @Produce json @Success 200 {array} Job @Router /api/v1/cron [get]

func (*Handler) ListWrapped

func (h *Handler) ListWrapped(c echo.Context) error

ListWrapped returns cron jobs in the legacy CLI response shape.

func (*Handler) PeekService

func (h *Handler) PeekService() *Service

PeekService returns the current service if it has already been initialized. It never triggers lazy initialization.

func (*Handler) RegisterRoutes

func (h *Handler) RegisterRoutes(g *echo.Group)

RegisterRoutes registers cron routes.

func (*Handler) SetIdleReclaim

func (h *Handler) SetIdleReclaim(idleAfter time.Duration)

SetIdleReclaim configures idle reclaim for the lazily initialized cron service.

func (*Handler) SetServiceInitHook

func (h *Handler) SetServiceInitHook(fn func(*Service))

SetServiceInitHook configures a callback that runs once the lazy service is created.

func (*Handler) Status

func (h *Handler) Status(c echo.Context) error

Status returns scheduler status in the legacy CLI response shape.

func (*Handler) Trigger

func (h *Handler) Trigger(c echo.Context) error

Trigger manually triggers a cron job. @Summary Trigger cron job @Tags cron @Param id path string true "Job ID" @Success 200 {object} map[string]string @Failure 404 {object} map[string]string @Router /api/v1/cron/{id}/trigger [post]

func (*Handler) Update

func (h *Handler) Update(c echo.Context) error

Update updates a cron job. @Summary Update cron job @Tags cron @Accept json @Produce json @Param id path string true "Job ID" @Param request body UpdateRequest true "Update request" @Success 200 {object} map[string]string @Failure 400 {object} map[string]string @Failure 404 {object} map[string]string @Router /api/v1/cron/{id} [put]

type Job

type Job struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	Description string                 `json:"description,omitempty"`
	Schedule    string                 `json:"schedule"` // Cron expression
	Handler     string                 `json:"handler"`  // Handler name
	Payload     map[string]interface{} `json:"payload,omitempty"`
	Status      JobStatus              `json:"status"`
	Enabled     bool                   `json:"enabled"`
	CreatedAt   time.Time              `json:"created_at"`
	UpdatedAt   time.Time              `json:"updated_at"`
	LastRunAt   *time.Time             `json:"last_run_at,omitempty"`
	NextRunAt   *time.Time             `json:"next_run_at,omitempty"`
	RunCount    int64                  `json:"run_count"`
	FailCount   int64                  `json:"fail_count"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
	// contains filtered or unexported fields
}

Job represents a scheduled job.

type JobExecution

type JobExecution struct {
	ID        string        `json:"id"`
	JobID     string        `json:"job_id"`
	StartedAt time.Time     `json:"started_at"`
	EndedAt   *time.Time    `json:"ended_at,omitempty"`
	Duration  time.Duration `json:"duration,omitempty"`
	Status    string        `json:"status"` // running, completed, failed
	Error     string        `json:"error,omitempty"`
	Result    interface{}   `json:"result,omitempty"`
}

JobExecution represents a single job execution.

type JobHandler

type JobHandler func(ctx context.Context, job *Job) (interface{}, error)

JobHandler is a function that handles job execution.

type JobStatus

type JobStatus string

JobStatus represents the status of a cron job.

const (
	// StatusActive indicates the job is active and scheduled.
	StatusActive JobStatus = "active"
	// StatusPaused indicates the job is paused.
	StatusPaused JobStatus = "paused"
	// StatusRunning indicates the job is currently running.
	StatusRunning JobStatus = "running"
)

type Service

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

Service manages cron jobs.

func NewService

func NewService(cfg Config, logger *zap.Logger) *Service

NewService creates a new cron service.

func (*Service) Config

func (s *Service) Config() Config

List returns all jobs.

func (*Service) Create

func (s *Service) Create(name, description, schedule, handler string, payload map[string]interface{}) (*Job, error)

Create creates a new cron job.

func (*Service) Delete

func (s *Service) Delete(id string) error

Delete deletes a job.

func (*Service) Disable

func (s *Service) Disable(id string) error

Disable disables a job.

func (*Service) Enable

func (s *Service) Enable(id string) error

Enable enables a job.

func (*Service) Get

func (s *Service) Get(id string) (*Job, bool)

Get returns a job by ID.

func (*Service) GetExecutions

func (s *Service) GetExecutions(jobID string, limit int) ([]*JobExecution, error)

GetExecutions returns executions for a job.

func (*Service) Handlers

func (s *Service) Handlers() []string

Handlers returns registered handler names.

func (*Service) List

func (s *Service) List() []*Job

List returns all jobs.

func (*Service) RegisterBuiltinHandlers

func (s *Service) RegisterBuiltinHandlers()

RegisterBuiltinHandlers registers all built-in job handlers. Security: Command handler is disabled by default. Enable with caution.

func (*Service) RegisterCommandHandler

func (s *Service) RegisterCommandHandler(config CommandSecurityConfig)

RegisterCommandHandler registers the command handler with security configuration. Security: This should only be called if command execution is explicitly needed.

func (*Service) RegisterHandler

func (s *Service) RegisterHandler(name string, handler JobHandler)

RegisterHandler registers a job handler.

func (*Service) SetEventPublisher

func (s *Service) SetEventPublisher(pub EventPublisher)

SetEventPublisher wires the SSE event publisher.

func (*Service) SetMessageInjector

func (s *Service) SetMessageInjector(inj inject.MessageInjector)

SetMessageInjector wires the conversation message injector.

func (*Service) Start

func (s *Service) Start() error

Start starts the cron service.

func (*Service) Stop

func (s *Service) Stop(ctx context.Context) error

Stop stops the cron service.

func (*Service) Trigger

func (s *Service) Trigger(id string) error

Trigger manually triggers a job.

func (*Service) Update

func (s *Service) Update(id, name, description, schedule string, payload map[string]interface{}) error

Update updates a job.

type SkillAdapter

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

SkillAdapter adapts the cron Service to builtin.CronServiceInterface. It supports lazy initialization — the service is resolved on first use.

func NewSkillAdapter

func NewSkillAdapter(resolve func() *Service) *SkillAdapter

NewSkillAdapter creates a new adapter that resolves the service lazily. The resolve function should trigger lazy init if needed (e.g. Handler.GetService()).

func (*SkillAdapter) Create

func (a *SkillAdapter) Create(name, description, schedule, handler string, payload map[string]interface{}) (builtin.CronJobInfo, error)

func (*SkillAdapter) Delete

func (a *SkillAdapter) Delete(id string) error

func (*SkillAdapter) Disable

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

func (*SkillAdapter) Enable

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

func (*SkillAdapter) Get

func (a *SkillAdapter) Get(id string) (builtin.CronJobInfo, bool)

func (*SkillAdapter) GetExecutions

func (a *SkillAdapter) GetExecutions(jobID string, limit int) ([]builtin.CronJobExecution, error)

func (*SkillAdapter) List

func (a *SkillAdapter) List() []builtin.CronJobInfo

func (*SkillAdapter) Trigger

func (a *SkillAdapter) Trigger(id string) error

type UpdateRequest

type UpdateRequest struct {
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Schedule    string                 `json:"schedule" validate:"required"`
	Payload     map[string]interface{} `json:"payload"`
}

UpdateRequest represents an update job request.

Jump to

Keyboard shortcuts

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