cron

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatDuration added in v0.3.1

func FormatDuration(d time.Duration) string

FormatDuration formats a duration in human-readable format

func GetBackoffDelay added in v0.3.1

func GetBackoffDelay(consecutiveErrors int) time.Duration

GetBackoffDelay calculates exponential backoff delay for consecutive errors

func ParseHumanDuration added in v0.3.1

func ParseHumanDuration(s string) (time.Duration, error)

ParseHumanDuration parses human-readable duration strings Supports: "30s", "5m", "2h", "1d", "1w"

Types

type CronConfig added in v0.3.1

type CronConfig struct {
	Enabled           bool          `json:"enabled"`
	StorePath         string        `json:"store_path,omitempty"`
	MaxConcurrentRuns int           `json:"max_concurrent_runs,omitempty"`
	SessionRetention  time.Duration `json:"session_retention,omitempty"` // Session cleanup retention
	RunLogConfig      RunLogConfig  `json:"run_log_config"`
	DefaultTimeout    time.Duration `json:"default_timeout"` // Default job timeout
}

CronConfig represents cron configuration

func DefaultCronConfig added in v0.3.1

func DefaultCronConfig() CronConfig

DefaultCronConfig returns default cron configuration

type Delivery added in v0.3.1

type Delivery struct {
	Mode         DeliveryMode `json:"mode"`
	WebhookURL   string       `json:"webhook_url,omitempty"`
	WebhookToken string       `json:"webhook_token,omitempty"`
	BestEffort   bool         `json:"best_effort,omitempty"` // Don't fail job on delivery error
}

Delivery configuration

type DeliveryMode added in v0.3.1

type DeliveryMode string

DeliveryMode defines how job results are delivered

const (
	DeliveryModeAnnounce DeliveryMode = "announce" // Send to chat channels
	DeliveryModeWebhook  DeliveryMode = "webhook"  // HTTP POST to URL
	DeliveryModeNone     DeliveryMode = "none"     // No delivery
)

type Job

type Job struct {
	ID            string        `json:"id"`
	Name          string        `json:"name"`
	Schedule      Schedule      `json:"schedule"`
	SessionTarget SessionTarget `json:"session_target"`
	WakeMode      WakeMode      `json:"wake_mode"`
	Payload       Payload       `json:"payload"`
	Delivery      *Delivery     `json:"delivery,omitempty"`
	State         JobState      `json:"state"`
	CreatedAt     time.Time     `json:"created_at"`
	UpdatedAt     time.Time     `json:"updated_at"`
}

Job represents a scheduled cron job

func (*Job) CalculateNextRun added in v0.3.1

func (j *Job) CalculateNextRun(from time.Time) (time.Time, error)

CalculateNextRun calculates the next run time based on schedule

func (*Job) IsOneShot added in v0.3.1

func (j *Job) IsOneShot() bool

IsOneShot returns true if this is a one-time job

func (*Job) IsRunning added in v0.3.1

func (j *Job) IsRunning() bool

IsRunning checks if the job is currently running

func (*Job) MarkCompleted added in v0.3.1

func (j *Job) MarkCompleted(now time.Time, status string, errMsg string)

MarkCompleted marks the job as completed with a status

func (*Job) MarkRunning added in v0.3.1

func (j *Job) MarkRunning(now time.Time)

MarkRunning marks the job as running

func (*Job) ShouldDisableOnComplete added in v0.3.1

func (j *Job) ShouldDisableOnComplete() bool

ShouldDisableOnComplete returns true if job should be disabled after terminal status

func (*Job) ShouldRun added in v0.3.1

func (j *Job) ShouldRun(now time.Time) bool

ShouldRun checks if the job should run at the given time

type JobExecutor added in v0.3.1

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

JobExecutor handles execution of cron jobs

func NewJobExecutor added in v0.3.1

func NewJobExecutor(bus *bus.MessageBus, runLogger *RunLogger, timeout time.Duration) *JobExecutor

NewJobExecutor creates a new job executor

func (*JobExecutor) Execute added in v0.3.1

func (e *JobExecutor) Execute(ctx context.Context, job *Job) error

Execute executes a cron job

type JobState added in v0.3.1

type JobState struct {
	Enabled           bool       `json:"enabled"`
	RunningAt         *time.Time `json:"running_at,omitempty"`          // Set when job is running
	LastRunAt         *time.Time `json:"last_run_at,omitempty"`         // Last successful run
	NextRunAt         *time.Time `json:"next_run_at,omitempty"`         // Next scheduled run
	ConsecutiveErrors int        `json:"consecutive_errors"`            // Count of consecutive errors
	RunCount          int        `json:"run_count"`                     // Total successful runs
	ErrorBackoffUntil *time.Time `json:"error_backoff_until,omitempty"` // Backoff for failed jobs
	LastStatus        string     `json:"last_status"`                   // Last run status: "ok", "error", "skipped"
	LastError         string     `json:"last_error,omitempty"`          // Last error message
}

JobState represents the current state of a job

type Payload added in v0.3.1

type Payload struct {
	Type PayloadType `json:"type"`

	// For system-event type
	SystemEventType string `json:"system_event_type,omitempty"`

	// For agent-turn type
	Message string `json:"message,omitempty"`
}

Payload defines what the job executes

type PayloadType added in v0.3.1

type PayloadType string

PayloadType defines the job payload type

const (
	PayloadTypeSystemEvent PayloadType = "system-event"
	PayloadTypeAgentTurn   PayloadType = "agent-turn"
)

type RunLog added in v0.3.1

type RunLog struct {
	RunID      string                 `json:"run_id"`
	JobID      string                 `json:"job_id"`
	JobName    string                 `json:"job_name"`
	StartedAt  time.Time              `json:"started_at"`
	FinishedAt time.Time              `json:"finished_at"`
	Status     string                 `json:"status"` // "ok", "error", "skipped"
	Error      string                 `json:"error,omitempty"`
	Duration   time.Duration          `json:"duration"`
	Metadata   map[string]interface{} `json:"metadata,omitempty"`
	// Additional telemetry
	Timestamp time.Time `json:"timestamp"`
}

RunLog represents a single run of a job

type RunLogConfig added in v0.3.1

type RunLogConfig struct {
	MaxBytes  int64 `json:"max_bytes,omitempty"`  // Max file size before rotation
	KeepLines int   `json:"keep_lines,omitempty"` // Max lines to keep per job
}

RunLogConfig represents run log configuration

type RunLogFilter added in v0.3.1

type RunLogFilter struct {
	JobID  string    `json:"job_id,omitempty"`
	After  time.Time `json:"after,omitempty"`
	Before time.Time `json:"before,omitempty"`
	Status string    `json:"status,omitempty"`
	Limit  int       `json:"limit,omitempty"`
	Offset int       `json:"offset,omitempty"`
}

RunLogFilter defines filters for querying run logs

type RunLogger added in v0.3.1

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

RunLogger handles logging of job runs

func NewRunLogger added in v0.3.1

func NewRunLogger(logDir string, config RunLogConfig) (*RunLogger, error)

NewRunLogger creates a new run logger

func (*RunLogger) DeleteJobLogs added in v0.3.1

func (l *RunLogger) DeleteJobLogs(jobID string) error

DeleteJobLogs removes all logs for a job

func (*RunLogger) LogRun added in v0.3.1

func (l *RunLogger) LogRun(log *RunLog) error

LogRun records a job run

func (*RunLogger) ReadLogs added in v0.3.1

func (l *RunLogger) ReadLogs(jobID string, filter RunLogFilter) ([]*RunLog, error)

ReadLogs reads run logs for a job

type Schedule

type Schedule struct {
	Type ScheduleType `json:"type"`

	// For "at" type
	At time.Time `json:"at,omitempty"`

	// For "every" type
	EveryDuration time.Duration `json:"every_duration,omitempty"`

	// For "cron" type
	CronExpression string `json:"cron_expression,omitempty"`
	Timezone       string `json:"timezone,omitempty"`

	// Stagger support (for load distribution)
	StaggerDuration time.Duration `json:"stagger_duration,omitempty"`
}

Schedule defines when a job should run

func (Schedule) MarshalJSON added in v0.3.1

func (s Schedule) MarshalJSON() ([]byte, error)

MarshalJSON implements custom JSON marshaling for Schedule

func (*Schedule) UnmarshalJSON added in v0.3.1

func (s *Schedule) UnmarshalJSON(data []byte) error

UnmarshalJSON implements custom JSON unmarshaling for Schedule

type ScheduleType added in v0.3.1

type ScheduleType string

ScheduleType represents the type of schedule

const (
	ScheduleTypeAt    ScheduleType = "at"    // One-shot at specific time
	ScheduleTypeEvery ScheduleType = "every" // Fixed interval
	ScheduleTypeCron  ScheduleType = "cron"  // Cron expression
)

type Service added in v0.3.1

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

Service manages cron jobs

func NewService added in v0.3.1

func NewService(config CronConfig, bus *bus.MessageBus) (*Service, error)

NewService creates a new cron service

func (*Service) AddJob added in v0.3.1

func (s *Service) AddJob(job *Job) error

AddJob adds a new job

func (*Service) DisableJob added in v0.3.1

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

DisableJob disables a job

func (*Service) EnableJob added in v0.3.1

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

EnableJob enables a job

func (*Service) GetJob added in v0.3.1

func (s *Service) GetJob(id string) (*Job, error)

GetJob retrieves a job by ID

func (*Service) GetRunLogs added in v0.3.1

func (s *Service) GetRunLogs(jobID string, filter RunLogFilter) ([]*RunLog, error)

GetRunLogs retrieves run logs for a job

func (*Service) GetStatus added in v0.3.1

func (s *Service) GetStatus() map[string]interface{}

GetStatus returns the current status of the cron service

func (*Service) ListJobs added in v0.3.1

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

ListJobs returns all jobs

func (*Service) RemoveJob added in v0.3.1

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

RemoveJob removes a job

func (*Service) RunJob added in v0.3.1

func (s *Service) RunJob(ctx context.Context, id string, force bool) error

RunJob executes a job immediately

func (*Service) Start added in v0.3.1

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

Start starts the cron service

func (*Service) Stop added in v0.3.1

func (s *Service) Stop() error

Stop stops the cron service

func (*Service) UpdateJob added in v0.3.1

func (s *Service) UpdateJob(id string, update func(*Job) error) error

UpdateJob updates an existing job

type SessionTarget added in v0.3.1

type SessionTarget string

SessionTarget defines where the job runs

const (
	SessionTargetMain     SessionTarget = "main"     // Run in main session
	SessionTargetIsolated SessionTarget = "isolated" // Run in dedicated isolated session
)

type Store added in v0.3.1

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

Store handles persistence of cron jobs

func NewStore added in v0.3.1

func NewStore(filePath string) (*Store, error)

NewStore creates a new job store

func (*Store) LoadJobs added in v0.3.1

func (s *Store) LoadJobs() ([]*Job, error)

LoadJobs loads all jobs from the store

func (*Store) SaveJobs added in v0.3.1

func (s *Store) SaveJobs(jobs []*Job) error

SaveJobs saves all jobs to the store (atomic write)

type WakeMode added in v0.3.1

type WakeMode string

WakeMode defines when to wake up for scheduled jobs

const (
	WakeModeNow           WakeMode = "now"            // Wake immediately
	WakeModeNextHeartbeat WakeMode = "next-heartbeat" // Wake on next heartbeat
)

Jump to

Keyboard shortcuts

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