### Initialize and Start Scheduler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Example of creating a scheduler, setting the runner, and starting execution. ```go scheduler := cron.New() scheduler.SetRunner(service.OnRunJob) scheduler.Start() ``` -------------------------------- ### Start() Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Initializes and starts the service components, including loading environment variables, resetting crashed jobs, and starting the cron scheduler. ```APIDOC ## func (s *Service) Start() ### Description Initializes and starts the service components. This method sets up the background context, loads environment variables, resets jobs left in a running state, and starts the cron scheduler. ### Parameters None ### Returns None (void) ``` -------------------------------- ### Start Service Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Initializes and starts the service components. ```go func (s *Service) Start() ``` ```go service := &core.Service{ Repository: repo, Scheduler: scheduler, Runners: map[string]domain.Runner{ "HTTP": httpRunner, }, } service.Start() ``` -------------------------------- ### Start HTTP server Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Initializes and starts the HTTP server on port 8080 with compression enabled. ```go func (s *Server) Start() ``` ```go server := &http.Server{ Service: service, } server.Start() // Server now listening on http://localhost:8080 ``` -------------------------------- ### Start Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Initializes the scheduler and begins job execution. ```go Start() ``` -------------------------------- ### Start() Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Starts the cron scheduler and begins background job execution. ```APIDOC ## Start() ### Description Starts the cron scheduler. Must be called after SetRunner() and after all initial jobs are added. ### Behavior - Calls underlying cron.Cron.Start() - Starts background goroutine for job execution ``` -------------------------------- ### ListJobs Usage Example Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Examples showing how to list all jobs or filter by collection and specific fields. ```go // List all jobs jobs, err := service.ListJobs("", []string{}) // List jobs with status and error rate jobs, err := service.ListJobs("col123", []string{"status", "errorRate"}) ``` -------------------------------- ### Start Service with Docker Compose Source: https://github.com/akornatskyy/scheduler/blob/master/README.md Starts the Scheduler service using Docker Compose. Assumes you are in the `deployments/docker` directory. Use `docker compose logs -f --tail=10` to view container output. ```sh cd deployments/docker docker compose up -d ``` -------------------------------- ### RetrieveVariable Usage Example Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Example showing how to retrieve a variable and handle potential errors. ```go variable, err := service.RetrieveVariable("var123") if err != nil { // Handle error } fmt.Printf("Value: %s\n", variable.Value) ``` -------------------------------- ### Configure Production Environment Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/configuration.md Example environment variables for production deployment. ```bash export DSN=postgresql://scheduler_user:secure_password@db.example.com:5432/scheduler?sslmode=require export SCHEDULER_AUTH_TOKEN=production-token export SCHEDULER_NOTIFICATION_URL=https://alerts.example.com export SCHEDULER_API_KEY=secure-api-key ``` -------------------------------- ### UpdateVariable Usage Example Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Example showing how to update a variable's value. ```go variable.Value = "new-secret-token" if err := service.UpdateVariable(variable); err != nil { // Handle error } ``` -------------------------------- ### Source Environment and Install Dependencies Source: https://github.com/akornatskyy/scheduler/blob/master/README.md Sources the local environment file to load variables and then installs project dependencies. This is required before building or running the service locally. ```sh source .env.local # or `. .env.local` make install ``` -------------------------------- ### GET / Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Serves the UI index.html file. ```APIDOC ## GET / ### Description Serves the UI index.html file. ### Method GET ### Endpoint / ### Response - **Content** (file) - index.html content ``` -------------------------------- ### Configure Development Environment Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/configuration.md Example environment variables for local development using a .env.local file. ```bash # .env.local file export DSN=postgres://postgres:@127.0.0.1:5432/scheduler?sslmode=disable export SCHEDULER_API_KEY=dev-key-123 export SCHEDULER_WEBHOOK_HOST=http://localhost:3000 ``` -------------------------------- ### DeleteVariable Usage Example Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Example showing how to delete a variable by its ID. ```go if err := service.DeleteVariable("var123"); err != nil { // Handle error } ``` -------------------------------- ### Copy Environment File Source: https://github.com/akornatskyy/scheduler/blob/master/README.md Copies the example environment file to a local file for configuration. This is the first step for running the service locally. ```sh cp .env.example .env.local ``` -------------------------------- ### PostgreSQL DSN Connection Strings Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/configuration.md Example connection strings for the DSN environment variable using libpq format. ```text postgres://user:password@localhost:5432/scheduler?sslmode=disable postgres://postgres:@127.0.0.1:5432/scheduler?sslmode=disable postgresql://username:password@hostname:5432/dbname?sslmode=require ``` -------------------------------- ### Run Development Web Server Source: https://github.com/akornatskyy/scheduler/blob/master/README.md Starts only the web development server with hot reloading. Ideal for frontend development. ```sh make dev-web ``` -------------------------------- ### GET /favicon.ico Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Serves the favicon. ```APIDOC ## GET /favicon.ico ### Description Serves the favicon. ### Method GET ### Endpoint /favicon.ico ### Response - **Content** (file) - favicon.ico content ``` -------------------------------- ### Start Scheduler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Initializes the scheduler and begins background job execution. Must be called after setting the runner and adding initial jobs. ```go func (s *cronSheduler) Start() ``` ```go scheduler.SetRunner(service.OnRunJob) scheduler.Add(job1) scheduler.Add(job2) scheduler.Start() // Jobs now execute on schedule ``` -------------------------------- ### UTC Timezone Configuration Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Example demonstrating that cron expressions are interpreted strictly in UTC. ```go // Schedule for 9 AM UTC daily schedule := "0 9 * * *" // Will execute at 09:00:00 UTC regardless of system timezone ``` -------------------------------- ### Iterate Scheduled Job IDs Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Example of listing and printing all currently scheduled job IDs. ```go ids := scheduler.ListIDs() for _, id := range ids { fmt.Printf("Scheduled: %s\n", id) } ``` -------------------------------- ### GET /js/*filepath Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Serves JavaScript bundle files from the compiled UI bundle. ```APIDOC ## GET /js/*filepath ### Description Serves JavaScript bundle files. ### Method GET ### Endpoint /js/*filepath ### Parameters #### Path Parameters - **filepath** (string) - Required - The path to the specific JavaScript file within apps/api/static/js/ ### Response - **Content** (file) - JavaScript file content ``` -------------------------------- ### Execute HTTP Action Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Defines the signature for the Run method and provides an example of executing an HTTP action with a specific request configuration. ```go func (runner *httpRunner) Run(ctx context.Context, a *domain.Action) error ``` ```go action := &domain.Action{ Type: "HTTP", Request: &domain.HTTPRequest{ Method: "POST", URI: "https://example.com/webhook", Headers: []*domain.NameValuePair{ {Name: "Content-Type", Value: "application/json"}, }, Body: `{"event": "job_executed"}`, }, } runner := http.NewRunner() if err := runner.Run(ctx, action); err != nil { // Handle error } ``` -------------------------------- ### Run Development API Server Source: https://github.com/akornatskyy/scheduler/blob/master/README.md Starts only the API server for development purposes. Useful if you only need to work on the backend. ```sh make dev-api ``` -------------------------------- ### Register Job Runner Callback Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Example of setting a runner function that executes jobs in a goroutine. ```go scheduler.SetRunner(func(j *domain.JobDefinition) { go service.OnRunJob(j) }) ``` -------------------------------- ### GET /collections Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md Retrieves a list of all collections. ```APIDOC ## GET /collections ### Description Retrieves a list of all collections. ### Method GET ### Endpoint /collections ### Response #### Success Response (200) - **items** (CollectionItem[]) - Array of collection items #### Response Fields (CollectionItem) - **id** (string) - Unique collection identifier - **name** (string) - Collection name - **state** (CollectionState) - Collection state (enabled or disabled) ``` -------------------------------- ### Run Development Mode Source: https://github.com/akornatskyy/scheduler/blob/master/README.md Starts both the API server and the web development server with hot reloading enabled. The API runs on port 8080 and the web server on port 3000. ```sh make dev ``` -------------------------------- ### Add Job to Scheduler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Example of adding a job definition with error handling for invalid schedules. ```go job := &domain.JobDefinition{ ID: "job123", Schedule: "0 9 * * *", // ... other fields } if err := scheduler.Add(job); err != nil { log.Printf("Invalid schedule: %v", err) } ``` -------------------------------- ### JSON Representation of Scheduler Job Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/types.md Example JSON structure demonstrating how job states, durations, and action configurations are serialized. ```json { "id": "job123", "name": "Daily Report", "collectionId": "col456", "state": "enabled", "schedule": "0 9 * * *", "action": { "type": "HTTP", "request": { "method": "POST", "uri": "https://example.com/webhook?id={{JobID}}", "headers": [ {"name": "Content-Type", "value": "application/json"}, {"name": "Authorization", "value": "Bearer {{token}}"} ], "body": "{\"data\": \"{{dataVar}}\"}" }, "retryPolicy": { "retryCount": 3, "retryInterval": "5s", "deadline": "20s" } } } ``` -------------------------------- ### List Jobs Handler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns an HTTP handler function for the GET /jobs endpoint. ```go func (s *Server) listJobs() http.HandlerFunc ``` -------------------------------- ### Remove Job from Scheduler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Example of removing a job by ID. ```go scheduler.Remove("job123") // Job no longer executes on schedule ``` -------------------------------- ### List Collections Handler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns an HTTP handler function for the GET /collections endpoint. ```go func (s *Server) listCollections() http.HandlerFunc ``` -------------------------------- ### List Variables Handler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns an HTTP handler function for the GET /variables endpoint. ```go func (s *Server) listVariables() http.HandlerFunc ``` -------------------------------- ### Example Error Response JSON Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Structure of the JSON response returned for validation errors. ```json { "domain": "scheduler", "type": "field", "location": "uri", "reason": "pattern", "message": "Must begin with http or https." } ``` -------------------------------- ### List Job History Handler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns an httprouter handle for the GET /jobs/:id/history endpoint with ETag support. ```go func (s *Server) listJobHistory() httprouter.Handle ``` -------------------------------- ### Retrieve Job Status Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Gets the current execution status and counts for a specific job. ```go RetrieveJobStatus(id string) (*JobStatus, error) ``` -------------------------------- ### Health Check Response Examples Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md JSON responses returned by the /health endpoint indicating service status. ```json {"status":"up"} ``` ```json {"status":"down","message":"database connection failed"} ``` -------------------------------- ### Retrieve Collection Handler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns an httprouter handle for the GET /collections/:id endpoint with ETag support. ```go func (s *Server) retrieveCollection() httprouter.Handle ``` -------------------------------- ### Serve UI Index Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns the index.html file for the UI. ```go func serveIndex() http.Handler ``` -------------------------------- ### Initialize Service with Dependency Injection Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Configures the service with a repository, scheduler, and runner map. Ensure all dependencies are initialized before passing them to the Service struct. ```go service := &core.Service{ Repository: postgres.NewRepository(dsn), Scheduler: cron.New(), Runners: map[string]domain.Runner{ "HTTP": http.NewRunner(), }, } ``` -------------------------------- ### Docker Compose Management Source: https://github.com/akornatskyy/scheduler/blob/master/deployments/docker/README.md Manages the scheduler application using Docker Compose. Sets the compose file environment variable, starts services in detached mode, and views logs. ```sh export COMPOSE_FILE=./deployments/docker/compose.yml docker compose up -d docker compose logs -f --tail=10 docker compose down ``` -------------------------------- ### Retrieve Job Status Handler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns an httprouter handle for the GET /jobs/:id/status endpoint with ETag support. ```go func (s *Server) retrieveJobStatus() httprouter.Handle ``` -------------------------------- ### Integrate Cron Scheduler in Go Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Demonstrates the lifecycle management of the scheduler, including initialization, job registration, updates, and graceful shutdown. ```go // In service startup scheduler := cron.New() scheduler.SetRunner(service.OnRunJob) // When job is created/enabled scheduler.Add(jobDefinition) // When job is updated scheduler.Add(jobDefinition) // Replaces old version // When job is deleted/disabled scheduler.Remove(jobID) // At shutdown scheduler.Stop() // Waits for running jobs ``` -------------------------------- ### GET /health Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md Checks the health status of the service. ```APIDOC ## GET /health ### Description Checks the health status of the service. ### Method GET ### Endpoint /health ### Response #### Success Response (200) - **status** (string) - Health status ("up" or "down") #### Error Response (503) - **status** (string) - Health status ("up" or "down") - **message** (string) - Error message describing the issue #### Response Example {"status":"up"} ``` -------------------------------- ### Serve JavaScript Bundle Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns JavaScript files from the compiled UI bundle. ```go func serveJavascript() http.Handler ``` -------------------------------- ### GET /jobs/:id/status Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Retrieves the status of a specific job. ```APIDOC ## GET /jobs/:id/status ### Description Retrieves the status of a job. ### Method GET ### Endpoint /jobs/:id/status ### Parameters #### Path Parameters - **id** (string) - Required - The job ID ### Response #### Success Response (200) - **JobStatus** (object) - The job status object ``` -------------------------------- ### RetrieveJobStatus(id string) Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Gets current execution status of a job. ```APIDOC ## RetrieveJobStatus(id string) ### Description Gets current execution status of a job. ### Parameters - **id** (string) - Job ID ### Returns - ***JobStatus** - Current status with execution counts - **error** - Query error or domain.ErrNotFound ``` -------------------------------- ### Serve Favicon Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns the favicon.ico file. ```go func serveFavicon() http.Handler ``` -------------------------------- ### GET /variables/:id Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md Retrieves details of a specific variable by its ID. ```APIDOC ## GET /variables/:id ### Description Retrieves the details of a specific variable. ### Method GET ### Endpoint /variables/:id ### Parameters #### Path Parameters - **id** (string) - Required - Variable identifier ``` -------------------------------- ### GET /collections/:id Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md Retrieves details of a specific collection by its ID. ```APIDOC ## GET /collections/:id ### Description Retrieves details of a specific collection by its ID. ### Method GET ### Endpoint /collections/:id ### Parameters #### Path Parameters - **id** (string) - Required - Collection identifier ### Response #### Success Response (200) - **id** (string) - Unique collection identifier - **name** (string) - Collection name - **state** (CollectionState) - Collection state - **updated** (time.Time) - Last update timestamp ``` -------------------------------- ### GET /jobs/:id Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md Retrieves the details of a specific job by its unique identifier. ```APIDOC ## GET /jobs/:id ### Description Retrieves the full definition of a specific job. ### Method GET ### Endpoint /jobs/:id ### Parameters #### Path Parameters - **id** (string) - Required - Job identifier ### Response #### Success Response (200) - **id** (string) - Unique job identifier - **name** (string) - Job name - **collectionId** (string) - Associated collection ID - **state** (JobState) - Job state - **schedule** (string) - Cron expression - **action** (Action) - Job action definition - **updated** (time.Time) - Last update timestamp ``` -------------------------------- ### Define Docker Build and Runtime Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/configuration.md Multi-stage Dockerfile for building the Go application and running it in an Alpine container. ```dockerfile FROM golang:1.24 AS builder WORKDIR /app COPY . . RUN make build FROM alpine:latest EXPOSE 8080 ENV DSN=postgresql://postgres:password@postgres:5432/scheduler?sslmode=disable COPY --from=builder /app/scheduler /usr/local/bin/ CMD ["scheduler"] ``` -------------------------------- ### GET /variables Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md Retrieves a list of variables, optionally filtered by collection ID. ```APIDOC ## GET /variables ### Description Retrieves a list of variables. Supports filtering by collectionId. ### Method GET ### Endpoint /variables ### Parameters #### Query Parameters - **collectionId** (string) - Optional - Filter variables by collection ID ### Response #### Success Response (200) - **items** (VariableItem[]) - Array of variable items ``` -------------------------------- ### GET /jobs/{id}/history Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/README.md Retrieves the execution history for a specific job. ```APIDOC ## GET /jobs/{id}/history ### Description Fetches the history of a specific job. ### Method GET ### Endpoint /jobs/{id}/history ### Parameters #### Path Parameters - **id** (string) - Required - The job ID ``` -------------------------------- ### Create Variable Definition and Usage Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Defines the method signature for creating a new variable and demonstrates initializing the struct before calling the service. ```go func (s *Service) CreateVariable(v *domain.Variable) error ``` ```go variable := &domain.Variable{ Name: "api_token", CollectionID: "col123", Value: "secret-token", } if err := service.CreateVariable(variable); err != nil { // Handle error } ``` -------------------------------- ### Delete Job History Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Removes execution history entries started before the specified time. ```go DeleteJobHistory(id string, before time.Time) error ``` -------------------------------- ### Add Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Adds or updates a job in the scheduler. ```go Add(j *JobDefinition) error ``` -------------------------------- ### Health Check Handler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns an HTTP handler function for the GET /health endpoint. ```go func (s *Server) health() http.HandlerFunc ``` -------------------------------- ### Apply Kubernetes Deployments Source: https://github.com/akornatskyy/scheduler/blob/master/deployments/k8s/README.md Use this command to apply all Kubernetes configurations defined in the specified directory. Ensure you are in the correct project directory. ```sh kubectl apply -f deployments/k8s ``` -------------------------------- ### Build Production Application Source: https://github.com/akornatskyy/scheduler/blob/master/README.md Builds both the web UI and the API server for production. The web app is compiled into the `apps/api/static` directory. ```sh make build ``` -------------------------------- ### Import Core Scheduler Packages Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/README.md Essential imports for accessing core, domain, and infrastructure components in Go. ```go import ( "github.com/akornatskyy/scheduler/internal/core" "github.com/akornatskyy/scheduler/internal/domain" "github.com/akornatskyy/scheduler/internal/infrastructure/cron" "github.com/akornatskyy/scheduler/internal/infrastructure/http" "github.com/akornatskyy/scheduler/internal/infrastructure/postgres" ) ``` -------------------------------- ### Handle ErrUnableCancelJob Response Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/errors.md Example JSON response format for an inability to cancel a running job. ```json { "domain": "scheduler", "type": "field", "location": "running", "reason": "not implemented", "message": "Unable to cancel the running job." } ``` -------------------------------- ### Initialize HTTP Runner Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Creates a new HTTP runner instance and assigns it to the service runners map. ```go func NewRunner() domain.Runner ``` ```go runners := map[string]domain.Runner{ "HTTP": http.NewRunner(), } service.Runners = runners ``` -------------------------------- ### Create Collection Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Creates a new collection and populates its ID if empty. ```go func (s *Service) CreateCollection(c *domain.Collection) error ``` ```go collection := &domain.Collection{ Name: "Daily Tasks", State: domain.CollectionStateEnabled, } if err := service.CreateCollection(collection); err != nil { // Handle error } // collection.ID is now populated ``` -------------------------------- ### Register HTTP routes Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Configures and returns the router instance containing all API endpoints. ```go func (s *Server) Routes() http.Handler ``` ```go router := server.Routes() // Can be used with http.ListenAndServe(":8080", router) ``` -------------------------------- ### Build Docker Image Source: https://github.com/akornatskyy/scheduler/blob/master/deployments/docker/README.md Builds a Docker image for the scheduler, tagging it with a specific version. Ensure the VERSION environment variable is set. ```sh docker build -t akorn/scheduler --build-arg VERSION=${VERSION} \ -f deployments/docker/Dockerfile . ``` -------------------------------- ### CreateCollection Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Creates a new collection and triggers a PostgreSQL NOTIFY event. ```go CreateCollection(c *Collection) error ``` -------------------------------- ### GET /jobs/:id/status Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md Retrieves the current status, run counts, and scheduling information for a specific job. ```APIDOC ## GET /jobs/:id/status ### Description Retrieves the current status, run counts, and scheduling information for a specific job. ### Method GET ### Endpoint /jobs/:id/status ### Parameters #### Path Parameters - **id** (string) - Required - Job identifier ### Response #### Success Response (200) - **updated** (time.Time) - Last status update timestamp - **running** (bool) - Whether the job is currently running - **runCount** (int) - Total number of times job has run - **errorCount** (int) - Total number of failed executions - **lastRun** (time.Time) - Timestamp of last execution - **nextRun** (time.Time) - Timestamp of next scheduled execution ``` -------------------------------- ### Define New Scheduler Interface Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Signature for creating a new cron scheduler instance. ```go func New() domain.Scheduler ``` -------------------------------- ### Create Job Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Inserts a new job into the database and triggers a PostgreSQL NOTIFY event. ```go CreateJob(j *JobDefinition) error ``` -------------------------------- ### Define Add Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Signature for adding or updating a job definition. ```go func (s *cronSheduler) Add(j *domain.JobDefinition) error ``` -------------------------------- ### CreateCollection(c *domain.Collection) Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Creates a new collection. ```APIDOC ## func (s *Service) CreateCollection(c *domain.Collection) error ### Description Creates a new collection. Validates the input, auto-generates an ID if missing, and persists the collection to the database. ### Parameters - **c** (*domain.Collection) - Required - Collection to create ### Returns - **error** - nil on success, error if operation fails ``` -------------------------------- ### Close Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Closes the database connection for graceful shutdown. ```go Close() error ``` -------------------------------- ### List Variables Definition and Usage Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Defines the method signature for retrieving variables associated with a collection and demonstrates iterating over the results. ```go func (s *Service) ListVariables(collectionID string) ([]*domain.VariableItem, error) ``` ```go variables, err := service.ListVariables("col123") if err != nil { // Handle error } for _, v := range variables { fmt.Printf("Variable: %s\n", v.Name) } ``` -------------------------------- ### ListCollections Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Retrieves a list of all collections. ```go ListCollections() ([]*CollectionItem, error) ``` -------------------------------- ### Set Database Connection String Source: https://github.com/akornatskyy/scheduler/blob/master/README.md Exports the database connection string as an environment variable. Ensure this is configured correctly for your local PostgreSQL instance. ```sh export DSN=postgres://postgres:@127.0.0.1:5432/scheduler?sslmode=disable ``` -------------------------------- ### POST /jobs Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md Creates a new job with a specified schedule and HTTP action. ```APIDOC ## POST /jobs ### Description Creates a new job definition. Requires a name, collectionId, state, schedule, and action details. ### Method POST ### Endpoint /jobs ### Request Body - **id** (string) - Optional - Job ID (auto-generated if omitted) - **name** (string) - Required - Job name - **collectionId** (string) - Required - Associated collection ID - **state** (JobState) - Required - Job state (enabled or disabled) - **schedule** (string) - Required - Cron expression - **action** (Action) - Required - Action to execute ### Response #### Success Response (201) - **id** (string) - The created job ID ``` -------------------------------- ### GET /jobs Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md Retrieves a list of jobs, optionally filtered by collection ID and including additional fields like status or error rate. ```APIDOC ## GET /jobs ### Description Retrieves a list of jobs. Supports filtering by collectionId and requesting optional fields. ### Method GET ### Endpoint /jobs ### Parameters #### Query Parameters - **collectionId** (string) - Optional - Filter jobs by collection ID - **fields** (string) - Optional - Comma-separated list of optional fields to include (status, errorRate) ### Response #### Success Response (200) - **items** (JobItem[]) - Array of job items ``` -------------------------------- ### Get Next Run Time Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Retrieves the next scheduled execution time for a specific job ID. Returns nil if the job is not found. ```go func (s *cronSheduler) NextRun(id string) *time.Time ``` ```go nextRun := scheduler.NextRun("job123") if nextRun != nil { fmt.Printf("Next run: %v\n", nextRun.Format(time.RFC3339)) } ``` -------------------------------- ### Apply ETagHandler Middleware Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Wraps a handler to provide ETag-based caching for list endpoints. ```go func ETagHandler(next http.Handler) http.HandlerFunc ``` ```go router.HandlerFunc("GET", "/collections", ETagHandler(s.listCollections())) ``` -------------------------------- ### POST /jobs Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Creates a new job. ```APIDOC ## POST /jobs ### Description Creates a new job. ### Method POST ### Endpoint /jobs ### Request Body - **JobDefinition** (object) - The job definition object ### Response #### Success Response (201) - **id** (string) - The ID of the created job ``` -------------------------------- ### HTTP Server Address Configuration Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Defines the hardcoded server address constant. ```go const ( addr = ":8080" ) ``` -------------------------------- ### System API Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md System health checks and static file serving. ```APIDOC ## GET /health ### Description Perform a health check on the service. ## GET / ### Description Serve the index.html file. ## GET /favicon.ico ### Description Serve the favicon. ## GET /js/*filepath ### Description Serve JavaScript bundles. ``` -------------------------------- ### CreateJob Method Definition and Usage Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Defines a new job with specific scheduling and action parameters. The ID is auto-generated if left empty. ```go func (s *Service) CreateJob(job *domain.JobDefinition) error ``` ```go job := &domain.JobDefinition{ Name: "Daily Webhook", CollectionID: "col123", State: domain.JobStateEnabled, Schedule: "0 9 * * *", Action: &domain.Action{ Type: "HTTP", Request: &domain.HTTPRequest{ Method: "POST", URI: "https://example.com/webhook?id={{.JobID}}", Headers: []*domain.NameValuePair{ {Name: "Content-Type", Value: "application/json"}, }, Body: `{"collection": "{{.CollectionID}}"}`, }, RetryPolicy: &domain.RetryPolicy{ RetryCount: 3, RetryInterval: domain.Duration(5 * time.Second), Deadline: domain.Duration(20 * time.Second), }, }, } if err := service.CreateJob(job); err != nil { // Handle error } ``` -------------------------------- ### New() Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Creates a new cron scheduler instance configured with UTC timezone. ```APIDOC ## func New() ### Description Creates a new cron scheduler instance. The scheduler is initialized with UTC timezone and an empty job map. ### Returns - `domain.Scheduler` - Configured cron scheduler ### Example ```go scheduler := cron.New() scheduler.SetRunner(service.OnRunJob) scheduler.Start() ``` ``` -------------------------------- ### Ping Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Checks database connectivity for health checks. ```go Ping() error ``` -------------------------------- ### Set Application Version Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/configuration.md Defines the application version variable, which can be overridden at compile time using ldflags. ```go var Version = "0.0.0-dev" ``` -------------------------------- ### Define ListIDs Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Signature for retrieving all scheduled job IDs. ```go func (s *cronSheduler) ListIDs() []string ``` -------------------------------- ### Exporting Scheduler Environment Variables Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/configuration.md Setting environment variables with the SCHEDULER_ prefix for template substitution. ```bash export SCHEDULER_API_TOKEN=secret123 export SCHEDULER_WEBHOOK_URL=https://example.com ``` -------------------------------- ### Stop Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Gracefully stops the scheduler, waiting for in-flight jobs to complete. ```go Stop() ``` -------------------------------- ### POST /collections Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md Creates a new collection. ```APIDOC ## POST /collections ### Description Creates a new collection. ### Method POST ### Endpoint /collections ### Request Body - **id** (string) - Optional - Collection ID (auto-generated if omitted) - **name** (string) - Required - Collection name - **state** (CollectionState) - Required - Must be "enabled" or "disabled" ### Response #### Success Response (201) - **id** (string) - The created collection ID ``` -------------------------------- ### CreateJob(j *JobDefinition) Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Creates a new job. ```APIDOC ## CreateJob(j *JobDefinition) ### Description Creates a new job. ### Parameters - **j** (*JobDefinition) - Job to create ### Returns - **error** - nil on success, domain.ErrConflict if ID exists ``` -------------------------------- ### CreateVariable Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Creates a new variable and may trigger scheduler updates. ```go CreateVariable(v *Variable) error ``` -------------------------------- ### Define Cron Scheduler Structures Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Internal structures for the cron scheduler implementation. ```go type cronSheduler struct { mu sync.Mutex c *cron.Cron jobs map[string]*cronJob runner func(*domain.JobDefinition) } type cronJob struct { id cron.EntryID j *domain.JobDefinition } ``` -------------------------------- ### Add(j *domain.JobDefinition) Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Adds or updates a job in the scheduler. ```APIDOC ## func (s *cronSheduler) Add(j *domain.JobDefinition) error ### Description Adds or updates a job in the scheduler. If the job ID exists and the timestamp is unchanged, the operation is idempotent. ### Parameters - **j** (*domain.JobDefinition) - Required - Job to add or update ### Returns - `error` - nil on success, error if cron expression is invalid ### Example ```go job := &domain.JobDefinition{ ID: "job123", Schedule: "0 9 * * *", } if err := scheduler.Add(job); err != nil { log.Printf("Invalid schedule: %v", err) } ``` ``` -------------------------------- ### Define Predefined UpdateEvents Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/types.md Commonly used connection-related event instances. ```go var ( Connected = &UpdateEvent{ObjectType: "connection", Operation: "connected"} Disconnected = &UpdateEvent{ObjectType: "connection", Operation: "disconnected"} Reconnected = &UpdateEvent{ObjectType: "connection", Operation: "reconnected"} ) ``` -------------------------------- ### Create a Job via HTTP POST Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/README.md Sends a JSON payload to define a new job with a schedule, HTTP action, and retry policy. ```bash POST /jobs Content-Type: application/json { "name": "Daily Report", "collectionId": "col123", "state": "enabled", "schedule": "0 9 * * *", "action": { "type": "HTTP", "request": { "method": "POST", "uri": "https://example.com/webhook?jobId={{.JobID}}", "headers": [ {"name": "Authorization", "value": "Bearer {{.api_token}}"} ], "body": "{\"collection\": \"{{.CollectionID}}\"}" }, "retryPolicy": { "retryCount": 3, "retryInterval": "5s", "deadline": "20s" } } } ``` -------------------------------- ### ListCollections() Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Lists all collections. ```APIDOC ## func (s *Service) ListCollections() ([]*domain.CollectionItem, error) ### Description Retrieves a list of all collections from the repository. ### Parameters None ### Returns - **[]*domain.CollectionItem** - Slice of collection items - **error** - Error if operation fails ``` -------------------------------- ### Define Run method signature in Go Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md The method signature for executing a job action, returning an error on failure. ```go Run(ctx context.Context, a *Action) error ``` -------------------------------- ### Define Action struct Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/types.md Defines the action a job performs, including request details and retry logic. ```go type Action struct { Type string `json:"type"` Request *HTTPRequest `json:"request"` RetryPolicy *RetryPolicy `json:"retryPolicy,omitempty"` } ``` -------------------------------- ### Create Job Handler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns an HTTP handler function for the POST /jobs endpoint. ```go func (s *Server) createJob() http.HandlerFunc ``` -------------------------------- ### Retrieve Job Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Fetches a single job definition by its ID. ```go RetrieveJob(id string) (*JobDefinition, error) ``` -------------------------------- ### List Leftover Jobs Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Identifies jobs that were running during a system crash; intended for startup recovery. ```go ListLeftOverJobs() ([]string, error) ``` -------------------------------- ### Define HTTPRequest struct Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/types.md Configures the HTTP request for job execution, supporting template variables in the body and headers. ```go type HTTPRequest struct { Method string `json:"method,omitempty"` URI string `json:"uri"` Headers []*NameValuePair `json:"headers,omitempty"` Body string `json:"body,omitempty"` } ``` -------------------------------- ### Create Collection Handler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns an HTTP handler function for the POST /collections endpoint. ```go func (s *Server) createCollection() http.HandlerFunc ``` -------------------------------- ### Define JobDefinition struct Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/types.md Represents a complete job definition including execution configuration. ```go type JobDefinition struct { JobItem Updated time.Time `json:"updated"` Action *Action `json:"action"` } ``` -------------------------------- ### NextRun Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Retrieves the next scheduled execution time for a specific job. ```go NextRun(id string) *time.Time ``` -------------------------------- ### Create Variable Handler Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Returns an HTTP handler function for the POST /variables endpoint. ```go func (s *Server) createVariable() http.HandlerFunc ``` -------------------------------- ### Retrieve Collection Definition and Usage Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Defines the method signature for fetching a collection by ID and demonstrates error handling for missing records. ```go func (s *Service) RetrieveCollection(id string) (*domain.Collection, error) ``` ```go collection, err := service.RetrieveCollection("abc123") if err == domain.ErrNotFound { // Handle not found } if err != nil { // Handle other errors } ``` -------------------------------- ### RetrieveJob Method Definition and Usage Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Fetches a job definition by its unique identifier. ```go func (s *Service) RetrieveJob(id string) (*domain.JobDefinition, error) ``` ```go job, err := service.RetrieveJob("job123") if err != nil { // Handle error } fmt.Printf("Job: %s (schedule: %s)\n", job.Name, job.Schedule) ``` -------------------------------- ### Port-Forward Kubernetes Services Source: https://github.com/akornatskyy/scheduler/blob/master/deployments/k8s/README.md These commands establish port forwarding to Kubernetes services, allowing local access to databases or applications. Use the appropriate service name and port. ```sh kubectl port-forward service/scheduler-db 5432 # apply sql scripts ``` ```sh kubectl port-forward service/scheduler 8080 ``` -------------------------------- ### Run a Job Immediately Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/README.md Triggers an immediate execution of a specific job by updating its status. ```bash PATCH /jobs/job123/status Content-Type: application/json If-Match: "abc123def456" { "running": true } ``` -------------------------------- ### POST /jobs Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/README.md Creates a new scheduled job with specific action and retry policies. ```APIDOC ## POST /jobs ### Description Creates a new job in the system. ### Method POST ### Endpoint /jobs ### Request Body - **name** (string) - Required - Name of the job - **collectionId** (string) - Required - ID of the collection - **state** (string) - Required - Job state (e.g., enabled) - **schedule** (string) - Required - Cron schedule expression - **action** (object) - Required - Job action configuration ### Request Example { "name": "Daily Report", "collectionId": "col123", "state": "enabled", "schedule": "0 9 * * *", "action": { "type": "HTTP", "request": { "method": "POST", "uri": "https://example.com/webhook?jobId={{.JobID}}", "headers": [{"name": "Authorization", "value": "Bearer {{.api_token}}"}], "body": "{\"collection\": \"{{.CollectionID}}\"}" }, "retryPolicy": { "retryCount": 3, "retryInterval": "5s", "deadline": "20s" } } } ``` -------------------------------- ### CreateJob(job *domain.JobDefinition) Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Creates a new job definition. The ID is auto-generated if empty, and the job is automatically scheduled if enabled. ```APIDOC ## CreateJob(job *domain.JobDefinition) ### Description Creates a new job definition. Validates job name, collectionID, state, schedule, and action details before persisting to the database. ### Parameters - **job** (*domain.JobDefinition) - Required - Job definition to create; ID auto-generated if empty ### Returns - **error** - nil on success, error if operation fails ``` -------------------------------- ### Define Missing Action Error Detail Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/errors.md Structure for reporting a missing required action object. ```go &errorstate.Detail{ Domain: "scheduler", Type: "field", Location: "action", Reason: "required", Message: "Required object cannot be null.", } ``` -------------------------------- ### List Job History Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Retrieves execution records for a job, ordered from newest to oldest. ```go ListJobHistory(id string) ([]*JobHistory, error) ``` -------------------------------- ### Define JobItem struct Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/types.md Represents a lightweight job definition used in list responses. ```go type JobItem struct { ID string `json:"id"` Name string `json:"name"` CollectionID string `json:"collectionId"` State JobState `json:"state"` Schedule string `json:"schedule"` Status *JobStatusCode `json:"status,omitempty"` ErrorRate *float32 `json:"errorRate,omitempty"` } ``` -------------------------------- ### ListVariables Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Lists all variables associated with a specific collection ID. ```go ListVariables(collectionID string) ([]*VariableItem, error) ``` -------------------------------- ### SetRunner Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Registers the callback function for job execution. ```go SetRunner(f func(*JobDefinition)) ``` ```go scheduler.SetRunner(service.OnRunJob) ``` -------------------------------- ### POST /variables Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/endpoints.md Creates a new variable. ```APIDOC ## POST /variables ### Description Creates a new variable in the system. ### Method POST ### Endpoint /variables ### Parameters #### Request Body - **id** (string) - Optional - Variable ID (auto-generated if omitted) - **name** (string) - Required - Variable name - **collectionId** (string) - Required - Associated collection ID - **value** (string) - Required - Variable value ``` -------------------------------- ### Clean Up Kubernetes Deployed Resources Source: https://github.com/akornatskyy/scheduler/blob/master/README.md Run this command to remove resources deployed to Kubernetes using `kubectl apply -f deployments/k8s`. ```bash kubectl delete -f deployments/k8s ``` -------------------------------- ### Health() Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Checks service health by verifying database connectivity. ```APIDOC ## func (s *Service) Health() error ### Description Checks service health by verifying database connectivity via Repository.Ping(). ### Parameters None ### Returns - **error** - nil if healthy, error if database is unavailable ``` -------------------------------- ### Repository Interface Definition Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md The primary interface defining all database operations for the scheduler. ```go type Repository interface { Ping() error Close() error ListCollections() ([]*CollectionItem, error) CreateCollection(c *Collection) error RetrieveCollection(id string) (*Collection, error) UpdateCollection(c *Collection) error DeleteCollection(id string) error ListVariables(collectionID string) ([]*VariableItem, error) MapVariables(collectionID string) (map[string]string, error) CreateVariable(v *Variable) error RetrieveVariable(id string) (*Variable, error) UpdateVariable(v *Variable) error DeleteVariable(id string) error ListJobs(collectionID string, fields []string) ([]*JobItem, error) CreateJob(j *JobDefinition) error RetrieveJob(id string) (*JobDefinition, error) UpdateJob(j *JobDefinition) error DeleteJob(id string) error RetrieveJobStatus(id string) (*JobStatus, error) ListLeftOverJobs() ([]string, error) ResetJobStatus(id string) error ListJobHistory(id string) ([]*JobHistory, error) DeleteJobHistory(id string, before time.Time) error AcquireJob(id string, deadline time.Duration) error AddJobHistory(*JobHistory) error } ``` -------------------------------- ### Define Runner interface in Go Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Defines the contract for job execution, requiring a context and an action pointer. ```go type Runner interface { Run(ctx context.Context, a *Action) error } ``` -------------------------------- ### Catching ErrNotFound in Go Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/errors.md Use this pattern to identify and handle 404 Not Found errors when resource retrieval or modification fails. ```go if err == domain.ErrNotFound { // Handle not found case } ``` -------------------------------- ### Define Collection struct Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/types.md Represents a complete collection entity including metadata. ```go type Collection struct { CollectionItem Updated time.Time } ``` -------------------------------- ### Implement writeError Function Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/http-server.md Internal function for mapping domain errors to HTTP status codes and logging. ```go func writeError(w http.ResponseWriter, err error) { // Internal error handling function } ``` -------------------------------- ### Define Subscriber interface in Go Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Defines the contract for handling database event subscriptions, including callback registration and lifecycle management. ```go type Subscriber interface { SetCallback(f func(*UpdateEvent) error) Start() Stop() } ``` -------------------------------- ### Stop() Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Gracefully shuts down all service components, cancels running jobs, and closes the database connection. ```APIDOC ## func (s *Service) Stop() ### Description Gracefully shuts down all service components. It cancels the background context, stops the scheduler, and closes the database connection. ### Parameters None ### Returns None (void) ``` -------------------------------- ### Configure Kubernetes Secret and Deployment Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/configuration.md Defines a Kubernetes Secret for database credentials and a Deployment that references the secret for environment variables. ```yaml apiVersion: v1 kind: Secret metadata: name: scheduler-db type: Opaque stringData: DSN: postgresql://user:password@postgres:5432/scheduler?sslmode=require --- apiVersion: apps/v1 kind: Deployment metadata: name: scheduler spec: containers: - name: scheduler image: scheduler:latest ports: - containerPort: 8080 env: - name: DSN valueFrom: secretKeyRef: name: scheduler-db key: DSN - name: SCHEDULER_CUSTOM_VAR value: "some-value" ``` -------------------------------- ### Job Execution Flow Diagram Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/scheduler.md Visual representation of the internal job execution lifecycle from cron trigger to history recording. ```text Cron Timer Tick ↓ Schedule Match ↓ cronSheduler.Run(jobDef) ↓ Runner Callback (service.OnRunJob) ↓ Acquire Lock + Execute HTTP Request ↓ Record History + Update Status ``` -------------------------------- ### Define Service struct Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md The Service struct orchestrates the scheduler components. ```go type Service struct { Repository domain.Repository Scheduler domain.Scheduler Runners map[string]domain.Runner // unexported fields for internal state } ``` -------------------------------- ### Define NameValuePair struct Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/types.md Represents a key-value pair used for HTTP headers. ```go type NameValuePair struct { Name string `json:"name"` Value string `json:"value"` } ``` -------------------------------- ### Update Collection Definition and Usage Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Defines the method signature for updating an existing collection and demonstrates modifying fields before persistence. ```go func (s *Service) UpdateCollection(c *domain.Collection) error ``` ```go collection.Name = "Updated Name" collection.State = domain.CollectionStateDisabled if err := service.UpdateCollection(collection); err != nil { // Handle error } ``` -------------------------------- ### Stop Service Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Gracefully shuts down all service components. ```go func (s *Service) Stop() ``` ```go // Graceful shutdown service.Stop() ``` -------------------------------- ### ListJobs Method Definition Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/service.md Method signature for listing jobs with optional collection filtering and field selection. ```go func (s *Service) ListJobs(collectionID string, fields []string) ([]*domain.JobItem, error) ``` -------------------------------- ### MapVariables Method Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/api-reference/domain.md Retrieves variables as a name-value map, useful for template substitution. ```go MapVariables(collectionID string) (map[string]string, error) ``` -------------------------------- ### Define Missing HTTP Request Error Detail Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/errors.md Structure for reporting a missing required HTTP request object. ```go &errorstate.Detail{ Domain: "scheduler", Type: "field", Location: "request", Reason: "required", Message: "Required object cannot be null.", } ``` -------------------------------- ### PATCH /jobs/{id}/status Source: https://github.com/akornatskyy/scheduler/blob/master/_autodocs/README.md Triggers a job to run immediately. ```APIDOC ## PATCH /jobs/{id}/status ### Description Updates the status of a job to trigger immediate execution. ### Method PATCH ### Endpoint /jobs/{id}/status ### Parameters #### Path Parameters - **id** (string) - Required - The job ID ### Request Example { "running": true } ```