cron

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: May 3, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package cron provides scheduled job execution for omniagent.

It supports cron expressions, one-time execution, and interval-based scheduling with actions that can send messages to sessions, call webhooks, or invoke registered tools.

Index

Constants

This section is empty.

Variables

View Source
var ErrJobNotFound = errors.New("job not found")

ErrJobNotFound is returned when a job is not found.

Functions

This section is empty.

Types

type Action

type Action struct {
	// Type is the action type.
	Type ActionType `json:"type"`

	// SessionID is the target session for send_message actions.
	SessionID string `json:"session_id,omitempty"`

	// Message is the content to send for send_message actions.
	Message string `json:"message,omitempty"`

	// WebhookURL is the target URL for call_webhook actions.
	WebhookURL string `json:"webhook_url,omitempty"`

	// WebhookMethod is the HTTP method (default: POST).
	WebhookMethod string `json:"webhook_method,omitempty"`

	// WebhookHeaders are additional headers for webhook requests.
	WebhookHeaders map[string]string `json:"webhook_headers,omitempty"`

	// WebhookBody is the request body for webhook requests.
	WebhookBody string `json:"webhook_body,omitempty"`

	// ToolName is the tool to invoke for call_tool actions.
	ToolName string `json:"tool_name,omitempty"`

	// ToolParams are the parameters to pass to the tool.
	ToolParams map[string]any `json:"tool_params,omitempty"`
}

Action defines what a job does when it runs.

func (*Action) Validate

func (a *Action) Validate() error

Validate checks if the action is valid.

type ActionType

type ActionType string

ActionType represents the type of action a job performs.

const (
	// ActionTypeSendMessage sends a message to a session via the agent.
	ActionTypeSendMessage ActionType = "send_message"

	// ActionTypeCallWebhook makes an HTTP request to a webhook URL.
	ActionTypeCallWebhook ActionType = "call_webhook"

	// ActionTypeCallTool invokes a registered tool.
	ActionTypeCallTool ActionType = "call_tool"
)

type Duration

type Duration time.Duration

Duration wraps time.Duration for JSON marshaling.

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON encodes the duration as a string.

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a duration string.

type ExecutionHandler

type ExecutionHandler func(ctx context.Context, job *Job) ExecutionResult

ExecutionHandler is a callback function invoked when a job executes.

type ExecutionResult

type ExecutionResult struct {
	// Success indicates if the execution completed successfully.
	Success bool `json:"success"`

	// Output is the result from the action.
	Output any `json:"output,omitempty"`

	// Error is the error message if execution failed.
	Error string `json:"error,omitempty"`

	// Duration is how long the execution took.
	Duration time.Duration `json:"duration"`

	// StartedAt is when the execution started.
	StartedAt time.Time `json:"started_at"`

	// FinishedAt is when the execution finished.
	FinishedAt time.Time `json:"finished_at"`
}

ExecutionResult represents the outcome of a job execution.

type Job

type Job struct {
	// ID is the unique identifier for the job.
	ID string `json:"id"`

	// Name is a human-readable name for the job.
	Name string `json:"name"`

	// Description provides additional context about the job.
	Description string `json:"description,omitempty"`

	// Schedule defines when the job runs.
	Schedule Schedule `json:"schedule"`

	// Action defines what the job does when it runs.
	Action Action `json:"action"`

	// Status is the current state of the job.
	Status JobStatus `json:"status"`

	// CreatedAt is when the job was created.
	CreatedAt time.Time `json:"created_at"`

	// UpdatedAt is when the job was last modified.
	UpdatedAt time.Time `json:"updated_at"`

	// LastRunAt is when the job last ran (nil if never run).
	LastRunAt *time.Time `json:"last_run_at,omitempty"`

	// NextRunAt is when the job is scheduled to run next (nil if not scheduled).
	NextRunAt *time.Time `json:"next_run_at,omitempty"`

	// RunCount is the total number of times the job has run.
	RunCount int64 `json:"run_count"`

	// LastError is the error from the last run (empty if successful).
	LastError string `json:"last_error,omitempty"`

	// Metadata contains arbitrary key-value pairs for extensibility.
	Metadata map[string]any `json:"metadata,omitempty"`
}

Job represents a scheduled job.

func NewJob

func NewJob(id, name string, schedule Schedule, action Action) *Job

NewJob creates a new job with the given parameters.

func (*Job) IsRecurring

func (j *Job) IsRecurring() bool

IsRecurring returns true if the job runs more than once.

func (*Job) Validate

func (j *Job) Validate() error

Validate checks if the job is valid.

type JobStatus

type JobStatus string

JobStatus represents the current state of a job.

const (
	// JobStatusEnabled indicates the job is active and will run according to schedule.
	JobStatusEnabled JobStatus = "enabled"

	// JobStatusDisabled indicates the job is inactive and will not run.
	JobStatusDisabled JobStatus = "disabled"

	// JobStatusRunning indicates the job is currently executing.
	JobStatusRunning JobStatus = "running"
)

type Schedule

type Schedule struct {
	// Cron is a cron expression (e.g., "0 9 * * *" for 9am daily).
	Cron string `json:"cron,omitempty"`

	// Once is a specific time for one-time execution.
	Once *time.Time `json:"once,omitempty"`

	// Interval is the duration between runs (e.g., 1h for hourly).
	Interval Duration `json:"interval,omitempty"`
}

Schedule defines when a job runs. Exactly one of Cron, Once, or Interval should be set.

type Scheduler

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

Scheduler manages scheduled job execution.

func NewScheduler

func NewScheduler(config SchedulerConfig) *Scheduler

NewScheduler creates a new scheduler.

func (*Scheduler) AddJob

func (s *Scheduler) AddJob(ctx context.Context, job *Job) error

AddJob adds a new job to the scheduler.

func (*Scheduler) DisableJob

func (s *Scheduler) DisableJob(ctx context.Context, id string) error

DisableJob disables a job without deleting it.

func (*Scheduler) EnableJob

func (s *Scheduler) EnableJob(ctx context.Context, id string) error

EnableJob enables a disabled job.

func (*Scheduler) GetJob

func (s *Scheduler) GetJob(ctx context.Context, id string) (*Job, error)

GetJob retrieves a job by ID.

func (*Scheduler) IsRunning

func (s *Scheduler) IsRunning() bool

IsRunning returns true if the scheduler is active.

func (*Scheduler) ListJobs

func (s *Scheduler) ListJobs(ctx context.Context) ([]*Job, error)

ListJobs returns all jobs.

func (*Scheduler) RemoveJob

func (s *Scheduler) RemoveJob(ctx context.Context, id string) error

RemoveJob removes a job from the scheduler.

func (*Scheduler) Start

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

Start loads jobs from the store and begins scheduling.

func (*Scheduler) Stop

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

Stop gracefully shuts down the scheduler.

func (*Scheduler) TriggerJob

func (s *Scheduler) TriggerJob(ctx context.Context, id string) (*ExecutionResult, error)

TriggerJob runs a job immediately, regardless of schedule.

func (*Scheduler) UpdateJob

func (s *Scheduler) UpdateJob(ctx context.Context, job *Job) error

UpdateJob updates an existing job.

type SchedulerConfig

type SchedulerConfig struct {
	// Store is the job storage backend.
	Store *Store

	// Handler is called when a job executes.
	// If nil, jobs will be logged but not executed.
	Handler ExecutionHandler

	// Location is the timezone for cron expressions.
	// If nil, uses time.Local.
	Location *time.Location
}

SchedulerConfig configures the scheduler.

type Skill

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

Skill provides cron job management tools.

func NewSkill

func NewSkill() *Skill

NewSkill creates a new cron skill.

func (*Skill) Close

func (s *Skill) Close() error

Close releases resources.

func (*Skill) Description

func (s *Skill) Description() string

Description returns a human-readable description.

func (*Skill) GetScheduler

func (s *Skill) GetScheduler() *Scheduler

GetScheduler returns the scheduler instance.

func (*Skill) Init

func (s *Skill) Init(ctx context.Context) error

Init initializes the skill.

func (*Skill) Name

func (s *Skill) Name() string

Name returns the skill identifier.

func (*Skill) SetExecutionHandler

func (s *Skill) SetExecutionHandler(handler ExecutionHandler)

SetExecutionHandler sets the handler for job execution. This should be called after NewSkill() and before Init().

func (*Skill) SetStorage

func (s *Skill) SetStorage(storage kvs.Store)

SetStorage implements compiled.StorageAware.

func (*Skill) Tools

func (s *Skill) Tools() []skill.Tool

Tools returns the tools provided by this skill.

type Store

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

Store manages persistent job storage.

func NewStore

func NewStore(config StoreConfig) *Store

NewStore creates a new job store.

func (*Store) ClearCache

func (s *Store) ClearCache()

ClearCache removes all cached jobs. This does not delete jobs from the backend.

func (*Store) Close

func (s *Store) Close() error

Close closes the underlying backend.

func (*Store) Count

func (s *Store) Count(ctx context.Context) (int, error)

Count returns the number of jobs.

func (*Store) Delete

func (s *Store) Delete(ctx context.Context, id string) error

Delete removes a job.

func (*Store) Get

func (s *Store) Get(ctx context.Context, id string) (*Job, error)

Get retrieves a job by ID. Returns ErrJobNotFound if the job doesn't exist.

func (*Store) List

func (s *Store) List(ctx context.Context) ([]*Job, error)

List returns all jobs. This requires the backend to implement kvs.ListableStore.

func (*Store) ListByStatus

func (s *Store) ListByStatus(ctx context.Context, status JobStatus) ([]*Job, error)

ListByStatus returns jobs with the given status.

func (*Store) ListEnabled

func (s *Store) ListEnabled(ctx context.Context) ([]*Job, error)

ListEnabled returns all enabled jobs.

func (*Store) Save

func (s *Store) Save(ctx context.Context, job *Job) error

Save persists a job to storage.

type StoreConfig

type StoreConfig struct {
	// Backend is the KVS storage backend.
	Backend kvs.Store
}

StoreConfig configures the job store.

Jump to

Keyboard shortcuts

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