schedule

package
v0.3.9 Latest Latest
Warning

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

Go to latest
Published: Jun 8, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package schedule provides parsing and execution of schedule tokens.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractScheduleTokens

func ExtractScheduleTokens(text string, location *time.Location) ([]*Token, []ParseWarning)

ExtractScheduleTokens finds all schedule tokens in text (helper function).

func IsImperativeLine

func IsImperativeLine(line string) bool

IsImperativeLine checks if a line is an imperative command.

func NextOccurrenceWithFilters

func NextOccurrenceWithFilters(schedule *Token, filters []*Token, now time.Time, loc *time.Location) time.Time

NextOccurrenceWithFilters finds the next occurrence that passes all filter constraints. It iterates through schedule candidates until finding one that passes all filters.

func TokenPattern

func TokenPattern() *regexp.Regexp

TokenPattern returns a regex pattern for matching schedule tokens.

Types

type ActionHandler

type ActionHandler func(pageID, actionName string, args []string, message string) error

ActionHandler is called when an action should be executed. The message parameter contains any blockquote content associated with the imperative.

type Cron

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

Cron manages scheduled jobs and their execution timing.

func NewCron

func NewCron(location *time.Location) *Cron

NewCron creates a new cron scheduler with the specified timezone.

func (*Cron) AddJob

func (c *Cron) AddJob(job *Job)

AddJob registers a new job with the scheduler.

func (*Cron) DisableJob

func (c *Cron) DisableJob(id string) bool

DisableJob disables a job without removing it.

func (*Cron) EnableJob

func (c *Cron) EnableJob(id string) bool

EnableJob enables a previously disabled job.

func (*Cron) GetJob

func (c *Cron) GetJob(id string) *Job

GetJob returns a job by ID.

func (*Cron) GetJobs

func (c *Cron) GetJobs() []*Job

GetJobs returns all registered jobs.

func (*Cron) GetJobsByPage

func (c *Cron) GetJobsByPage(pageID string) []*Job

GetJobsByPage returns all jobs for a specific page.

func (*Cron) IsRunning

func (c *Cron) IsRunning() bool

IsRunning returns whether the scheduler is currently running.

func (*Cron) JobCount

func (c *Cron) JobCount() int

JobCount returns the number of registered jobs.

func (*Cron) RemoveJob

func (c *Cron) RemoveJob(id string)

RemoveJob removes a job from the scheduler.

func (*Cron) RemoveJobsByPage

func (c *Cron) RemoveJobsByPage(pageID string)

RemoveJobsByPage removes all jobs for a specific page.

func (*Cron) SetErrorHandler

func (c *Cron) SetErrorHandler(fn ErrorHandler)

SetErrorHandler sets a callback for job execution errors. If not set, errors are logged to stderr.

func (*Cron) SetTimeFunc

func (c *Cron) SetTimeFunc(fn func() time.Time)

SetTimeFunc sets a custom time function (for testing).

func (*Cron) Start

func (c *Cron) Start(ctx context.Context)

Start begins the cron scheduler's ticker loop.

func (*Cron) Stop

func (c *Cron) Stop()

Stop halts the cron scheduler.

func (*Cron) Tick

func (c *Cron) Tick()

Tick manually triggers a check cycle (for testing).

func (*Cron) UpdateJobToken

func (c *Cron) UpdateJobToken(id string, token *Token) bool

UpdateJobToken updates a job's schedule token and recalculates next run.

type ErrorHandler

type ErrorHandler func(job *Job, err error)

ErrorHandler is called when a job execution fails.

type Imperative

type Imperative struct {
	Type         ImperativeType
	Token        *Token   // The primary schedule token (e.g., @daily:9am)
	FilterTokens []*Token // Filter tokens (e.g., @weekdays, @weekends)
	Message      string   // For Notify: inline message, or blockquote content
	ActionName   string   // For RunAction: the action name
	Args         []string // For RunAction: optional arguments
	Line         int      // Source line number
	Raw          string   // Original line text
}

Imperative represents a parsed imperative line.

func ExtractImperatives

func ExtractImperatives(content string, location *time.Location) []*Imperative

ExtractImperatives returns all imperative lines from content.

func ParseImperativeLine

func ParseImperativeLine(line string, location *time.Location) *Imperative

ParseImperativeLine parses a single imperative line (helper function).

type ImperativeType

type ImperativeType int

ImperativeType indicates the type of imperative command.

const (
	ImperativeNotify ImperativeType = iota
	ImperativeRunAction
)

type Job

type Job struct {
	ID      string
	PageID  string
	Line    string // The imperative line (e.g., "Notify @daily:9am Check email")
	Token   *Token
	Filters []*Token // Filter tokens (e.g., @weekdays, @weekends) that constrain when job runs
	NextRun time.Time
	LastRun *time.Time
	Enabled bool
	Handler JobHandler
}

Job represents a scheduled job to be executed.

type JobHandler

type JobHandler func(job *Job) error

JobHandler is called when a job should execute.

type NotificationHandler

type NotificationHandler func(pageID, message string) error

NotificationHandler is called when a notification should be sent.

type OffsetSpec

type OffsetSpec struct {
	Duration time.Duration
}

OffsetSpec represents a relative time offset.

type ParseWarning

type ParseWarning struct {
	Message string
	Line    int
	Column  int
	Token   string
}

ParseWarning represents a non-fatal parsing issue.

type Parser

type Parser struct {
	Location *time.Location
	Warnings []ParseWarning
}

Parser parses schedule tokens from text.

func NewParser

func NewParser(location *time.Location) *Parser

NewParser creates a new schedule parser with the specified timezone.

func (*Parser) ParseText

func (p *Parser) ParseText(text string) ([]*Token, error)

ParseText extracts schedule tokens from markdown text, skipping code blocks.

func (*Parser) ParseToken

func (p *Parser) ParseToken(s string) (*Token, error)

ParseToken parses a single schedule token string.

type RecurSpec

type RecurSpec struct {
	Days       []time.Weekday // For weekly: specific days
	DayOfMonth int            // For monthly: day number (1-31)
	Month      time.Month     // For yearly: month
	Day        int            // For yearly: day of month
	Time       *TimeSpec      // Time to trigger
}

RecurSpec represents a recurrence pattern.

type Runner

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

Runner manages scheduled job execution.

func NewRunner

func NewRunner(cfg RunnerConfig) *Runner

NewRunner creates a new schedule runner.

func (*Runner) AddJob

func (r *Runner) AddJob(job *Job)

AddJob adds a pre-configured job to the scheduler. This is useful when jobs are created externally (e.g., from parsed Page imperatives).

func (*Runner) GetAllJobs

func (r *Runner) GetAllJobs() []*Job

GetAllJobs returns all scheduled jobs.

func (*Runner) GetImperatives

func (r *Runner) GetImperatives(pageID string) []*Imperative

GetImperatives returns all imperatives for a page.

func (*Runner) GetJobsForPage

func (r *Runner) GetJobsForPage(pageID string) []*Job

GetJobsForPage returns all jobs for a specific page.

func (*Runner) GetWarnings

func (r *Runner) GetWarnings() []ParseWarning

GetWarnings returns any parsing warnings.

func (*Runner) ParsePage

func (r *Runner) ParsePage(pageID, content string) ([]*Imperative, error)

ParsePage extracts and registers imperative schedules from page content.

func (*Runner) RemovePage

func (r *Runner) RemovePage(pageID string)

RemovePage removes all schedules for a page.

func (*Runner) SetActionHandler

func (r *Runner) SetActionHandler(h ActionHandler)

SetActionHandler sets the callback for action execution.

func (*Runner) SetNotificationHandler

func (r *Runner) SetNotificationHandler(h NotificationHandler)

SetNotificationHandler sets the callback for notifications.

func (*Runner) SetTimeFunc

func (r *Runner) SetTimeFunc(fn func() time.Time)

SetTimeFunc sets a custom time function (for testing).

func (*Runner) Start

func (r *Runner) Start(ctx context.Context) error

Start begins the schedule runner.

func (*Runner) Stop

func (r *Runner) Stop() error

Stop halts the schedule runner.

func (*Runner) Tick

func (r *Runner) Tick()

Tick manually triggers a schedule check (for testing).

type RunnerConfig

type RunnerConfig struct {
	Location *time.Location
	StateDir string // Directory for state persistence (optional)
}

RunnerConfig configures a new Runner.

type TimeSpec

type TimeSpec struct {
	Hour   int
	Minute int
}

TimeSpec represents a time of day.

func (*TimeSpec) String

func (ts *TimeSpec) String() string

String returns a human-readable representation of TimeSpec.

type Token

type Token struct {
	Raw       string      // Original token text (e.g., "@daily:9am")
	Type      TokenType   // Type of schedule
	Time      *TimeSpec   // Specific time (if applicable)
	Recurring *RecurSpec  // Recurrence pattern (if applicable)
	Offset    *OffsetSpec // Relative offset (if applicable)
	Date      *time.Time  // Specific date (if applicable)
	Line      int         // Source line number
	Column    int         // Source column number
}

Token represents a parsed schedule token.

func (*Token) IsFilterToken

func (t *Token) IsFilterToken() bool

IsFilterToken returns true if this token is a filter modifier (not a schedule).

func (*Token) NextOccurrence

func (t *Token) NextOccurrence(now time.Time, loc *time.Location) time.Time

NextOccurrence calculates the next occurrence of this schedule token.

func (*Token) PassesFilter

func (t *Token) PassesFilter(candidate time.Time) bool

PassesFilter checks if a candidate time passes this filter token's constraints. Returns true if the token is not a filter or if the candidate matches the filter.

type TokenType

type TokenType int

TokenType indicates the kind of schedule token.

const (
	TokenRelative TokenType = iota // @today, @tomorrow, @yesterday
	TokenWeekday                   // @monday, @tuesday, etc.
	TokenISODate                   // @2024-03-15
	TokenTime                      // @9am, @9:30pm
	TokenOffset                    // @in:2hours, @in:30min
	TokenDaily                     // @daily:9am
	TokenWeekly                    // @weekly:mon,wed
	TokenMonthly                   // @monthly:1st, @monthly:15
	TokenYearly                    // @yearly:mar-15
	TokenWeekdays                  // @weekdays - filter: Mon-Fri only
	TokenWeekends                  // @weekends - filter: Sat-Sun only
)

func (TokenType) String

func (t TokenType) String() string

String returns a human-readable representation of the token.

Jump to

Keyboard shortcuts

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