cron

package
v0.0.0-...-f5fff41 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendCronRunLog

func AppendCronRunLog(ctx context.Context, backend StoreBackend, path string, entry CronRunLogEntry, maxBytes int64, keepLines int) error

AppendCronRunLog appends a log entry and prunes if too large.

func ComputeNextRunAtMs

func ComputeNextRunAtMs(schedule CronSchedule, nowMs int64) *int64

ComputeNextRunAtMs returns the next run time in unix ms.

func ResolveCronRunLogDir

func ResolveCronRunLogDir(storePath string) string

ResolveCronRunLogDir returns runs/ directory next to store.

func ResolveCronRunLogPath

func ResolveCronRunLogPath(storePath, jobID string) string

ResolveCronRunLogPath returns runs/<jobId>.jsonl next to store.

func ResolveCronStorePath

func ResolveCronStorePath(storePath string) string

ResolveCronStorePath resolves the virtual JSON store path.

func SaveCronStore

func SaveCronStore(ctx context.Context, backend StoreBackend, storePath string, store CronStoreFile) error

SaveCronStore writes the JSON store.

Types

type CronDelivery

type CronDelivery struct {
	Mode       CronDeliveryMode `json:"mode"`
	Channel    string           `json:"channel,omitempty"`
	To         string           `json:"to,omitempty"`
	BestEffort *bool            `json:"bestEffort,omitempty"`
}

CronDelivery controls how isolated runs announce results.

type CronDeliveryMode

type CronDeliveryMode string

CronDeliveryMode defines isolated job delivery behavior.

const (
	CronDeliveryNone     CronDeliveryMode = "none"
	CronDeliveryAnnounce CronDeliveryMode = "announce"
)

type CronDeliveryPatch

type CronDeliveryPatch struct {
	Mode       *CronDeliveryMode `json:"mode,omitempty"`
	Channel    *string           `json:"channel,omitempty"`
	To         *string           `json:"to,omitempty"`
	BestEffort *bool             `json:"bestEffort,omitempty"`
}

CronDeliveryPatch defines partial delivery updates.

type CronEvent

type CronEvent struct {
	JobID       string
	Action      string
	RunAtMs     int64
	DurationMs  int64
	Status      string
	Error       string
	Summary     string
	NextRunAtMs int64
}

CronEvent is emitted on job changes.

type CronJob

type CronJob struct {
	ID             string            `json:"id"`
	AgentID        string            `json:"agentId,omitempty"`
	Name           string            `json:"name"`
	Description    string            `json:"description,omitempty"`
	Enabled        bool              `json:"enabled"`
	DeleteAfterRun bool              `json:"deleteAfterRun,omitempty"`
	CreatedAtMs    int64             `json:"createdAtMs"`
	UpdatedAtMs    int64             `json:"updatedAtMs"`
	Schedule       CronSchedule      `json:"schedule"`
	SessionTarget  CronSessionTarget `json:"sessionTarget"`
	WakeMode       CronWakeMode      `json:"wakeMode"`
	Payload        CronPayload       `json:"payload"`
	Delivery       *CronDelivery     `json:"delivery,omitempty"`
	State          CronJobState      `json:"state"`
}

CronJob defines a stored job.

type CronJobCreate

type CronJobCreate struct {
	AgentID        *string           `json:"agentId,omitempty"`
	Name           string            `json:"name,omitempty"`
	Description    *string           `json:"description,omitempty"`
	Enabled        *bool             `json:"enabled,omitempty"`
	DeleteAfterRun *bool             `json:"deleteAfterRun,omitempty"`
	Schedule       CronSchedule      `json:"schedule"`
	SessionTarget  CronSessionTarget `json:"sessionTarget"`
	WakeMode       CronWakeMode      `json:"wakeMode,omitempty"`
	Payload        CronPayload       `json:"payload"`
	Delivery       *CronDelivery     `json:"delivery,omitempty"`
	State          *CronJobState     `json:"state,omitempty"`
}

CronJobCreate is input for creating jobs.

func NormalizeCronJobCreate

func NormalizeCronJobCreate(raw CronJobCreate) CronJobCreate

NormalizeCronJobCreate applies OpenClaw-like defaults.

func NormalizeCronJobCreateRaw

func NormalizeCronJobCreateRaw(raw any) (CronJobCreate, error)

NormalizeCronJobCreateRaw normalizes raw input into a CronJobCreate.

type CronJobPatch

type CronJobPatch struct {
	AgentID        *string            `json:"agentId,omitempty"`
	Name           *string            `json:"name,omitempty"`
	Description    *string            `json:"description,omitempty"`
	Enabled        *bool              `json:"enabled,omitempty"`
	DeleteAfterRun *bool              `json:"deleteAfterRun,omitempty"`
	Schedule       *CronSchedule      `json:"schedule,omitempty"`
	SessionTarget  *CronSessionTarget `json:"sessionTarget,omitempty"`
	WakeMode       *CronWakeMode      `json:"wakeMode,omitempty"`
	Payload        *CronPayloadPatch  `json:"payload,omitempty"`
	Delivery       *CronDeliveryPatch `json:"delivery,omitempty"`
	State          *CronJobState      `json:"state,omitempty"`
}

CronJobPatch defines partial updates.

func NormalizeCronJobPatchRaw

func NormalizeCronJobPatchRaw(raw any) (CronJobPatch, error)

NormalizeCronJobPatchRaw normalizes raw input into a CronJobPatch.

type CronJobState

type CronJobState struct {
	NextRunAtMs    *int64 `json:"nextRunAtMs,omitempty"`
	RunningAtMs    *int64 `json:"runningAtMs,omitempty"`
	LastRunAtMs    *int64 `json:"lastRunAtMs,omitempty"`
	LastStatus     string `json:"lastStatus,omitempty"`
	LastError      string `json:"lastError,omitempty"`
	LastDurationMs *int64 `json:"lastDurationMs,omitempty"`
}

CronJobState tracks runtime state.

type CronPayload

type CronPayload struct {
	Kind                string `json:"kind"`
	Text                string `json:"text,omitempty"`
	Message             string `json:"message,omitempty"`
	Model               string `json:"model,omitempty"`
	Thinking            string `json:"thinking,omitempty"`
	TimeoutSeconds      *int   `json:"timeoutSeconds,omitempty"`
	AllowUnsafeExternal *bool  `json:"allowUnsafeExternalContent,omitempty"`
}

CronPayload defines the job action.

type CronPayloadPatch

type CronPayloadPatch struct {
	Kind                string  `json:"kind"`
	Text                *string `json:"text,omitempty"`
	Message             *string `json:"message,omitempty"`
	Model               *string `json:"model,omitempty"`
	Thinking            *string `json:"thinking,omitempty"`
	TimeoutSeconds      *int    `json:"timeoutSeconds,omitempty"`
	AllowUnsafeExternal *bool   `json:"allowUnsafeExternalContent,omitempty"`
}

CronPayloadPatch defines partial payload updates.

type CronRunLogEntry

type CronRunLogEntry struct {
	TS          int64  `json:"ts"`
	JobID       string `json:"jobId"`
	Action      string `json:"action"`
	Status      string `json:"status,omitempty"`
	Error       string `json:"error,omitempty"`
	Summary     string `json:"summary,omitempty"`
	RunAtMs     int64  `json:"runAtMs,omitempty"`
	DurationMs  int64  `json:"durationMs,omitempty"`
	NextRunAtMs int64  `json:"nextRunAtMs,omitempty"`
}

CronRunLogEntry mirrors OpenClaw's log format.

func ParseCronRunLogEntries

func ParseCronRunLogEntries(raw string, limit int, jobID string) []CronRunLogEntry

ParseCronRunLogEntries parses recent entries from a jsonl log payload.

func ReadCronRunLogEntries

func ReadCronRunLogEntries(ctx context.Context, backend StoreBackend, path string, limit int, jobID string) ([]CronRunLogEntry, error)

ReadCronRunLogEntries reads recent entries from a jsonl log.

type CronSchedule

type CronSchedule struct {
	Kind     string `json:"kind"`
	At       string `json:"at,omitempty"`
	EveryMs  int64  `json:"everyMs,omitempty"`
	AnchorMs *int64 `json:"anchorMs,omitempty"`
	Expr     string `json:"expr,omitempty"`
	TZ       string `json:"tz,omitempty"`
}

CronSchedule defines when a cron job should run.

type CronService

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

CronService schedules jobs and runs them with a worker pool. The scheduler never executes jobs inline; it only enqueues tasks.

func NewCronService

func NewCronService(deps CronServiceDeps) *CronService

NewCronService creates a new cron service.

func (*CronService) Add

func (c *CronService) Add(input CronJobCreate) (CronJob, error)

Add creates a job.

func (*CronService) List

func (c *CronService) List(includeDisabled bool) ([]CronJob, error)

List returns jobs.

func (*CronService) Remove

func (c *CronService) Remove(id string) (bool, error)

Remove deletes a job.

func (*CronService) Run

func (c *CronService) Run(id string, mode string) (bool, string, error)

Run executes a job if due (or forced). This call blocks until the run completes (or errors).

func (*CronService) Start

func (c *CronService) Start() error

Start initializes the scheduler. It is safe to call Start multiple times.

func (*CronService) Status

func (c *CronService) Status() (bool, string, int, *int64, error)

Status returns scheduler status.

func (*CronService) Stop

func (c *CronService) Stop()

Stop stops the scheduler and waits for workers to exit.

func (*CronService) Update

func (c *CronService) Update(id string, patch CronJobPatch) (CronJob, error)

Update modifies a job.

func (*CronService) Wake

func (c *CronService) Wake(mode string, text string) (bool, error)

Wake enqueues a system event.

type CronServiceDeps

type CronServiceDeps struct {
	NowMs             func() int64
	Log               Logger
	StorePath         string
	Store             StoreBackend
	MaxConcurrentRuns int
	CronEnabled       bool

	// Optional hard timeout override (unix ms). If nil, cron derives a default from job config.
	ResolveJobTimeoutMs func(job CronJob) int64

	EnqueueSystemEvent  func(ctx context.Context, text string, agentID string) error
	RequestHeartbeatNow func(ctx context.Context, reason string)
	RunHeartbeatOnce    func(ctx context.Context, reason string) HeartbeatRunResult
	RunIsolatedAgentJob func(ctx context.Context, job CronJob, message string) (status string, summary string, outputText string, err error)

	OnEvent func(evt CronEvent)
}

CronServiceDeps provides integration hooks.

type CronSessionTarget

type CronSessionTarget string

CronSessionTarget defines where a cron job runs.

const (
	CronSessionMain     CronSessionTarget = "main"
	CronSessionIsolated CronSessionTarget = "isolated"
)

type CronStoreFile

type CronStoreFile struct {
	Version int       `json:"version"`
	Jobs    []CronJob `json:"jobs"`
}

CronStoreFile defines the JSON store format.

func LoadCronStore

func LoadCronStore(ctx context.Context, backend StoreBackend, storePath string) (CronStoreFile, error)

LoadCronStore reads the JSON store, tolerating missing files.

type CronWakeMode

type CronWakeMode string

CronWakeMode defines how the heartbeat is triggered after a main job.

const (
	CronWakeNextHeartbeat CronWakeMode = "next-heartbeat"
	CronWakeNow           CronWakeMode = "now"
)

type HeartbeatRunResult

type HeartbeatRunResult struct {
	Status string
	Reason string
}

HeartbeatRunResult mirrors OpenClaw heartbeat results.

type Logger

type Logger interface {
	Debug(msg string, fields ...any)
	Info(msg string, fields ...any)
	Warn(msg string, fields ...any)
	Error(msg string, fields ...any)
}

Logger matches OpenClaw logger shape.

type StoreBackend

type StoreBackend interface {
	Read(ctx context.Context, path string) ([]byte, bool, error)
	Write(ctx context.Context, path string, data []byte) error
	List(ctx context.Context, prefix string) ([]StoreEntry, error)
}

StoreBackend provides key-value storage access for cron state.

type StoreEntry

type StoreEntry struct {
	Key  string
	Data []byte
}

StoreEntry represents a key-value entry returned by List.

type TimestampValidationResult

type TimestampValidationResult struct {
	Ok      bool
	Message string
}

TimestampValidationResult mirrors OpenClaw timestamp validation output.

func ValidateSchedule

func ValidateSchedule(schedule CronSchedule) TimestampValidationResult

ValidateSchedule validates the schedule's timezone and cron expression (if applicable).

func ValidateScheduleTimestamp

func ValidateScheduleTimestamp(schedule CronSchedule, nowMs int64) TimestampValidationResult

ValidateScheduleTimestamp validates "at" schedules. Rejects timestamps that are more than 1 minute in the past or 10 years in the future.

Jump to

Keyboard shortcuts

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