Skip to content

Modern Docker Management, Designed for Everyone

refactor: move general settings to job scheduler category (#1310)

Kyle Mendell04fb9724f603
diff --git a/backend/internal/bootstrap/jobs_bootstrap.go b/backend/internal/bootstrap/jobs_bootstrap.go
index 17a66773c..22c692040 100644
--- a/backend/internal/bootstrap/jobs_bootstrap.go
+++ b/backend/internal/bootstrap/jobs_bootstrap.go
@@ -40,7 +40,8 @@ func registerJobs(appCtx context.Context, scheduler *job.Scheduler, appServices
slog.ErrorContext(appCtx, "Failed to register analytics heartbeat job", "error", err)
}
- if err := job.RegisterEventCleanupJob(appCtx, scheduler, appServices.Event); err != nil {
+ eventCleanupJob := job.NewEventCleanupJob(scheduler, appServices.Event, appServices.Settings)
+ if err := eventCleanupJob.Register(appCtx); err != nil {
slog.ErrorContext(appCtx, "Failed to register event cleanup job", "error", err)
}
@@ -48,6 +49,22 @@ func registerJobs(appCtx context.Context, scheduler *job.Scheduler, appServices
slog.ErrorContext(appCtx, "Failed to register filesystem watcher job", "error", err)
}
+ if appServices.JobSchedule != nil {
+ appServices.JobSchedule.OnJobSchedulesChanged = func(ctx context.Context) {
+ if !appConfig.AgentMode {
+ if err := environmentHealthJob.Reschedule(ctx); err != nil {
+ slog.WarnContext(ctx, "Failed to reschedule environment-health job", "error", err)
+ }
+ }
+ if err := analyticsJob.Reschedule(ctx); err != nil {
+ slog.WarnContext(ctx, "Failed to reschedule analytics heartbeat job", "error", err)
+ }
+ if err := eventCleanupJob.Reschedule(ctx); err != nil {
+ slog.WarnContext(ctx, "Failed to reschedule event cleanup job", "error", err)
+ }
+ }
+ }
+
appServices.Settings.OnImagePollingSettingsChanged = func(ctx context.Context) {
if err := imagePollingJob.Reschedule(ctx); err != nil {
slog.WarnContext(ctx, "Failed to reschedule image-polling job", "error", err)
diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.go
index c946c2eb6..d33617ee6 100644
--- a/backend/internal/bootstrap/router_bootstrap.go
+++ b/backend/internal/bootstrap/router_bootstrap.go
@@ -102,6 +102,7 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {
Version: appServices.Version,
Environment: appServices.Environment,
Settings: appServices.Settings,
+ JobSchedule: appServices.JobSchedule,
SettingsSearch: appServices.SettingsSearch,
ContainerRegistry: appServices.ContainerRegistry,
Template: appServices.Template,
diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.go
index 0395cae5b..a2cee2256 100644
--- a/backend/internal/bootstrap/services_bootstrap.go
+++ b/backend/internal/bootstrap/services_bootstrap.go
@@ -17,6 +17,7 @@ type Services struct {
Project *services.ProjectService
Environment *services.EnvironmentService
Settings *services.SettingsService
+ JobSchedule *services.JobService
SettingsSearch *services.SettingsSearchService
CustomizeSearch *services.CustomizeSearchService
Container *services.ContainerService
@@ -48,6 +49,7 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Config
if err != nil {
return nil, nil, fmt.Errorf("failed to settings service: %w", err)
}
+ svcs.JobSchedule = services.NewJobService(db, svcs.Settings, cfg)
svcs.SettingsSearch = services.NewSettingsSearchService()
svcs.CustomizeSearch = services.NewCustomizeSearchService()
svcs.AppImages = services.NewApplicationImagesService(resources.FS, svcs.Settings)
diff --git a/backend/internal/huma/handlers/job_schedules.go b/backend/internal/huma/handlers/job_schedules.go
new file mode 100644
index 000000000..c2a227b31
--- /dev/null
+++ b/backend/internal/huma/handlers/job_schedules.go
@@ -0,0 +1,83 @@
+package handlers
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/danielgtaylor/huma/v2"
+ "github.com/getarcaneapp/arcane/backend/internal/services"
+ "github.com/getarcaneapp/arcane/types/base"
+ "github.com/getarcaneapp/arcane/types/jobschedule"
+)
+
+type GetJobSchedulesOutput struct {
+ Body jobschedule.Config
+}
+
+type UpdateJobSchedulesInput struct {
+ Body jobschedule.Update `doc:"Job schedule update data"`
+}
+
+type UpdateJobSchedulesOutput struct {
+ Body base.ApiResponse[jobschedule.Config]
+}
+
+func RegisterJobSchedules(api huma.API, jobSvc *services.JobService) {
+ h := &JobSchedulesHandler{jobService: jobSvc}
+
+ huma.Register(api, huma.Operation{
+ OperationID: "get-job-schedules",
+ Method: http.MethodGet,
+ Path: "/job-schedules",
+ Summary: "Get job schedules",
+ Description: "Get configured intervals (in minutes) for background jobs",
+ Tags: []string{"JobSchedules"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.Get)
+
+ huma.Register(api, huma.Operation{
+ OperationID: "update-job-schedules",
+ Method: http.MethodPut,
+ Path: "/job-schedules",
+ Summary: "Update job schedules",
+ Description: "Update background job intervals and reschedule running jobs",
+ Tags: []string{"JobSchedules"},
+ Security: []map[string][]string{
+ {"BearerAuth": {}},
+ {"ApiKeyAuth": {}},
+ },
+ }, h.Update)
+}
+
+type JobSchedulesHandler struct {
+ jobService *services.JobService
+}
+
+func (h *JobSchedulesHandler) Get(ctx context.Context, _ *struct{}) (*GetJobSchedulesOutput, error) {
+ if h.jobService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+ cfg := h.jobService.GetJobSchedules(ctx)
+ return &GetJobSchedulesOutput{Body: cfg}, nil
+}
+
+func (h *JobSchedulesHandler) Update(ctx context.Context, input *UpdateJobSchedulesInput) (*UpdateJobSchedulesOutput, error) {
+ if h.jobService == nil {
+ return nil, huma.Error500InternalServerError("service not available")
+ }
+
+ cfg, err := h.jobService.UpdateJobSchedules(ctx, input.Body)
+ if err != nil {
+ return nil, huma.Error400BadRequest(err.Error())
+ }
+
+ return &UpdateJobSchedulesOutput{
+ Body: base.ApiResponse[jobschedule.Config]{
+ Success: true,
+ Data: cfg,
+ },
+ }, nil
+}
diff --git a/backend/internal/huma/huma.go b/backend/internal/huma/huma.go
index 191d54344..e6e342e2f 100644
--- a/backend/internal/huma/huma.go
+++ b/backend/internal/huma/huma.go
@@ -125,6 +125,7 @@ type Services struct {
Version *services.VersionService
Environment *services.EnvironmentService
Settings *services.SettingsService
+ JobSchedule *services.JobService
SettingsSearch *services.SettingsSearchService
ContainerRegistry *services.ContainerRegistryService
Template *services.TemplateService
@@ -280,6 +281,7 @@ func registerHandlers(api huma.API, svc *Services) {
var versionSvc *services.VersionService
var environmentSvc *services.EnvironmentService
var settingsSvc *services.SettingsService
+ var jobScheduleSvc *services.JobService
var settingsSearchSvc *services.SettingsSearchService
var containerRegistrySvc *services.ContainerRegistryService
var templateSvc *services.TemplateService
@@ -309,6 +311,7 @@ func registerHandlers(api huma.API, svc *Services) {
versionSvc = svc.Version
environmentSvc = svc.Environment
settingsSvc = svc.Settings
+ jobScheduleSvc = svc.JobSchedule
settingsSearchSvc = svc.SettingsSearch
containerRegistrySvc = svc.ContainerRegistry
templateSvc = svc.Template
@@ -342,6 +345,7 @@ func registerHandlers(api huma.API, svc *Services) {
handlers.RegisterImages(api, dockerSvc, imageSvc, imageUpdateSvc, settingsSvc)
handlers.RegisterImageUpdates(api, imageUpdateSvc)
handlers.RegisterSettings(api, settingsSvc, settingsSearchSvc, environmentSvc, cfg)
+ handlers.RegisterJobSchedules(api, jobScheduleSvc)
handlers.RegisterVolumes(api, dockerSvc, volumeSvc)
handlers.RegisterContainers(api, containerSvc, dockerSvc)
handlers.RegisterNetworks(api, networkSvc, dockerSvc)
diff --git a/backend/internal/job/analytics_job.go b/backend/internal/job/analytics_job.go
index 8bf3896ce..e62a654bc 100644
--- a/backend/internal/job/analytics_job.go
+++ b/backend/internal/job/analytics_job.go
@@ -19,7 +19,7 @@ import (
const (
AnalyticsJobName = "analytics-heartbeat"
defaultHeartbeatEndpoint = "https://checkin.getarcane.app/heartbeat"
- analyticsInterval = 24 * time.Hour
+ defaultAnalyticsInterval = 24 * time.Hour
)
type AnalyticsJob struct {
@@ -51,13 +51,20 @@ func NewAnalyticsJob(
func (j *AnalyticsJob) Register(ctx context.Context) error {
if j.cfg.AnalyticsDisabled || !j.cfg.Environment.IsProdEnvironment() {
slog.InfoContext(ctx, "analytics disabled or not in production; heartbeat job not registered", "analyticsDisabled", j.cfg.AnalyticsDisabled, "env", j.cfg.Environment)
+ j.scheduler.RemoveJobByName(AnalyticsJobName)
return nil
}
+ intervalMinutes := j.settingsService.GetIntSetting(ctx, "analyticsHeartbeatInterval", int(defaultAnalyticsInterval/time.Minute))
+ interval := time.Duration(intervalMinutes) * time.Minute
+ if interval < 60*time.Minute {
+ interval = defaultAnalyticsInterval
+ }
+
j.scheduler.RemoveJobByName(AnalyticsJobName)
- jobDefinition := gocron.DurationJob(analyticsInterval)
- slog.InfoContext(ctx, "registering analytics heartbeat job", "jobName", AnalyticsJobName, "interval", analyticsInterval.String(), "endpoint", j.heartbeatURL)
+ jobDefinition := gocron.DurationJob(interval)
+ slog.InfoContext(ctx, "registering analytics heartbeat job", "jobName", AnalyticsJobName, "interval", interval.String(), "endpoint", j.heartbeatURL)
return j.scheduler.RegisterJob(
ctx,
@@ -68,6 +75,24 @@ func (j *AnalyticsJob) Register(ctx context.Context) error {
)
}
+func (j *AnalyticsJob) Reschedule(ctx context.Context) error {
+ if j.cfg.AnalyticsDisabled || !j.cfg.Environment.IsProdEnvironment() {
+ j.scheduler.RemoveJobByName(AnalyticsJobName)
+ return nil
+ }
+
+ intervalMinutes := j.settingsService.GetIntSetting(ctx, "analyticsHeartbeatInterval", int(defaultAnalyticsInterval/time.Minute))
+ interval := time.Duration(intervalMinutes) * time.Minute
+ if interval < 60*time.Minute {
+ interval = defaultAnalyticsInterval
+ }
+
+ slog.InfoContext(ctx, "analytics heartbeat settings changed; rescheduling",
+ "jobName", AnalyticsJobName, "interval", interval.String())
+
+ return j.scheduler.RescheduleDurationJobByName(ctx, AnalyticsJobName, interval, j.Execute, false)
+}
+
func (j *AnalyticsJob) Execute(parentCtx context.Context) error {
if j.cfg.AnalyticsDisabled || !j.cfg.Environment.IsProdEnvironment() {
slog.InfoContext(parentCtx, "analytics disabled or not in production; skipping heartbeat", "analyticsDisabled", j.cfg.AnalyticsDisabled, "env", j.cfg.Environment)
diff --git a/backend/internal/job/event_cleanup_job.go b/backend/internal/job/event_cleanup_job.go
index cfcb6f70a..b01763871 100644
--- a/backend/internal/job/event_cleanup_job.go
+++ b/backend/internal/job/event_cleanup_job.go
@@ -12,47 +12,70 @@ import (
const EventCleanupJobName = "EventCleanup"
-func RegisterEventCleanupJob(
- ctx context.Context,
- scheduler *Scheduler,
- eventService *services.EventService,
-) error {
- slog.InfoContext(ctx, "Registering event cleanup job", "jobName", EventCleanupJobName)
-
- taskFunc := func(jobCtx context.Context) error {
- slog.InfoContext(jobCtx, "Running event cleanup job", "jobName", EventCleanupJobName)
-
- // Delete events older than 36 hours
- olderThan := 36 * time.Hour
- if err := eventService.DeleteOldEvents(jobCtx, olderThan); err != nil {
- slog.ErrorContext(jobCtx, "Failed to delete old events", "jobName", EventCleanupJobName, "olderThan", olderThan.String(), "error", err)
- return err
- }
-
- slog.InfoContext(jobCtx, "Event cleanup job completed successfully",
- "jobName", EventCleanupJobName,
- "olderThan", olderThan.String())
- return nil
+type EventCleanupJob struct {
+ scheduler *Scheduler
+ eventService *services.EventService
+ settingsService *services.SettingsService
+}
+
+func NewEventCleanupJob(scheduler *Scheduler, eventService *services.EventService, settingsService *services.SettingsService) *EventCleanupJob {
+ return &EventCleanupJob{
+ scheduler: scheduler,
+ eventService: eventService,
+ settingsService: settingsService,
}
+}
+
+func (j *EventCleanupJob) Register(ctx context.Context) error {
+ interval := j.getInterval(ctx)
+
+ slog.InfoContext(ctx, "Registering event cleanup job", "jobName", EventCleanupJobName, "interval", interval.String(), "retention", "36h")
- // Run every 6 hours to keep the cleanup regular but not too frequent
- jobDefinition := gocron.DurationJob(6 * time.Hour)
+ // ensure single instance
+ j.scheduler.RemoveJobByName(EventCleanupJobName)
- err := scheduler.RegisterJob(
+ jobDefinition := gocron.DurationJob(interval)
+ err := j.scheduler.RegisterJob(
ctx,
EventCleanupJobName,
jobDefinition,
- taskFunc,
+ j.Execute,
false, // Don't run immediately on startup
)
-
if err != nil {
return fmt.Errorf("failed to register event cleanup job %q: %w", EventCleanupJobName, err)
}
- slog.InfoContext(ctx, "Event cleanup job registered successfully",
+ return nil
+}
+
+func (j *EventCleanupJob) Reschedule(ctx context.Context) error {
+ interval := j.getInterval(ctx)
+ slog.InfoContext(ctx, "event cleanup settings changed; rescheduling", "jobName", EventCleanupJobName, "interval", interval.String())
+ return j.scheduler.RescheduleDurationJobByName(ctx, EventCleanupJobName, interval, j.Execute, false)
+}
+
+func (j *EventCleanupJob) getInterval(ctx context.Context) time.Duration {
+ minutes := j.settingsService.GetIntSetting(ctx, "eventCleanupInterval", 360)
+ interval := time.Duration(minutes) * time.Minute
+ if interval < 5*time.Minute {
+ interval = 6 * time.Hour
+ }
+ return interval
+}
+
+func (j *EventCleanupJob) Execute(ctx context.Context) error {
+ slog.InfoContext(ctx, "Running event cleanup job", "jobName", EventCleanupJobName)
+
+ // Delete events older than 36 hours
+ olderThan := 36 * time.Hour
+ if err := j.eventService.DeleteOldEvents(ctx, olderThan); err != nil {
+ slog.ErrorContext(ctx, "Failed to delete old events", "jobName", EventCleanupJobName, "olderThan", olderThan.String(), "error", err)
+ return err
+ }
+
+ slog.InfoContext(ctx, "Event cleanup job completed successfully",
"jobName", EventCleanupJobName,
- "interval", "6h",
- "retention", "36h")
+ "olderThan", olderThan.String())
return nil
}
diff --git a/backend/internal/models/settings.go b/backend/internal/models/settings.go
index 774ffc5b2..ff263ebd1 100644
--- a/backend/internal/models/settings.go
+++ b/backend/internal/models/settings.go
@@ -44,23 +44,25 @@ func (s SettingVariable) AsDurationSeconds() time.Duration {
type Settings struct {
// General category
- ProjectsDirectory SettingVariable `key:"projectsDirectory" meta:"label=Projects Directory;type=text;keywords=projects,directory,path,folder,location,storage,files,compose,docker-compose;category=general;description=Configure where project files are stored" catmeta:"id=general;title=General;icon=settings;url=/settings/general;description=Core application settings and configuration"`
+ ProjectsDirectory SettingVariable `key:"projectsDirectory" meta:"label=Projects Directory;type=text;keywords=projects,directory,path,folder,location,storage,files,compose,docker-compose;category=internal;description=Configure where project files are stored"`
DiskUsagePath SettingVariable `key:"diskUsagePath" meta:"label=Disk Usage Path;type=text;keywords=disk,usage,path,storage,folder,files;category=general;description=Path used for disk usage calculations"`
BaseServerURL SettingVariable `key:"baseServerUrl" meta:"label=Base Server URL;type=text;keywords=base,url,server,domain,host,endpoint,address,link;category=general;description=Set the base URL for the application"`
EnableGravatar SettingVariable `key:"enableGravatar" meta:"label=Enable Gravatar;type=boolean;keywords=gravatar,avatar,profile,picture,image,user,photo;category=general;description=Enable Gravatar profile pictures for users"`
DefaultShell SettingVariable `key:"defaultShell" meta:"label=Default Shell;type=text;keywords=shell,default,shellpath,path,login;category=general;description=Default shell to use for commands"`
- EnvironmentHealthInterval SettingVariable `key:"environmentHealthInterval" meta:"label=Environment Health Check Interval;type=number;keywords=environment,health,check,interval,frequency,heartbeat,status,monitoring,uptime;category=general;description=How often to check environment connectivity in minutes (default: 2)"`
+ EnvironmentHealthInterval SettingVariable `key:"environmentHealthInterval" meta:"label=Environment Health Check Interval;type=number;keywords=environment,health,check,interval,frequency,heartbeat,status,monitoring,uptime,jobs,schedule;category=jobschedule;description=How often to check environment connectivity in minutes (default: 2)" catmeta:"id=jobschedule;title=Job Schedule;icon=jobs;url=/settings/jobs;description=Configure how often Arcane background jobs run"`
AccentColor SettingVariable `key:"accentColor,public,local" meta:"label=Accent Color;type=text;keywords=color,accent,theme,css,appearance,ui;category=general;description=Primary accent color for UI"`
// Docker category
- AutoUpdate SettingVariable `key:"autoUpdate" meta:"label=Auto Update;type=boolean;keywords=auto,update,automatic,upgrade,refresh,restart,deploy;category=internal;description=Automatically update containers when new images are available"`
- AutoUpdateInterval SettingVariable `key:"autoUpdateInterval" meta:"label=Auto Update Interval;type=number;keywords=auto,update,interval,frequency,schedule,automatic,timing;category=internal;description=Interval between automatic updates"`
- PollingEnabled SettingVariable `key:"pollingEnabled" meta:"label=Enable Polling;type=boolean;keywords=polling,check,monitor,watch,scan,detection,automatic;category=internal;description=Enable automatic checking for image updates"`
- PollingInterval SettingVariable `key:"pollingInterval" meta:"label=Polling Interval;type=number;keywords=interval,frequency,schedule,time,minutes,period,delay;category=internal;description=How often to check for image updates"`
- AutoInjectEnv SettingVariable `key:"autoInjectEnv" meta:"label=Auto Inject Env Variables;type=boolean;keywords=auto,inject,env,environment,variables,interpolation;category=internal;description=Automatically inject project .env variables into all containers (default: false)"`
- PruneMode SettingVariable `key:"dockerPruneMode" meta:"label=Docker Prune Action;type=select;keywords=prune,cleanup,clean,remove,delete,unused,dangling,space,disk;category=internal;description=Configure how unused Docker images are cleaned up"`
- MaxImageUploadSize SettingVariable `key:"maxImageUploadSize" meta:"label=Max Image Upload Size;type=number;keywords=upload,size,limit,maximum,image,tar,file,megabytes,mb,storage;category=internal;description=Maximum size in MB for image archive uploads (default: 500)"`
- DockerHost SettingVariable `key:"dockerHost,public,envOverride" meta:"label=Docker Host;type=text;keywords=docker,host,daemon,socket,unix,remote;category=internal;description=URI for Docker daemon"`
+ AutoUpdate SettingVariable `key:"autoUpdate" meta:"label=Auto Update;type=boolean;keywords=auto,update,automatic,upgrade,refresh,restart,deploy;category=internal;description=Automatically update containers when new images are available"`
+ AutoUpdateInterval SettingVariable `key:"autoUpdateInterval" meta:"label=Auto Update Interval;type=number;keywords=auto,update,interval,frequency,schedule,automatic,timing;category=internal;description=Interval between automatic updates"`
+ PollingEnabled SettingVariable `key:"pollingEnabled" meta:"label=Enable Polling;type=boolean;keywords=polling,check,monitor,watch,scan,detection,automatic;category=internal;description=Enable automatic checking for image updates"`
+ PollingInterval SettingVariable `key:"pollingInterval" meta:"label=Polling Interval;type=number;keywords=interval,frequency,schedule,time,minutes,period,delay;category=internal;description=How often to check for image updates"`
+ EventCleanupInterval SettingVariable `key:"eventCleanupInterval" meta:"label=Event Cleanup Interval;type=number;keywords=events,cleanup,retention,interval,frequency,schedule,history,logs,jobs;category=jobschedule;description=How often to delete old events in minutes"`
+ AnalyticsHeartbeatInterval SettingVariable `key:"analyticsHeartbeatInterval" meta:"label=Analytics Heartbeat Interval;type=number;keywords=analytics,heartbeat,interval,frequency,schedule,telemetry,jobs;category=jobschedule;description=How often to send the anonymous analytics heartbeat in minutes"`
+ AutoInjectEnv SettingVariable `key:"autoInjectEnv" meta:"label=Auto Inject Env Variables;type=boolean;keywords=auto,inject,env,environment,variables,interpolation;category=internal;description=Automatically inject project .env variables into all containers (default: false)"`
+ PruneMode SettingVariable `key:"dockerPruneMode" meta:"label=Docker Prune Action;type=select;keywords=prune,cleanup,clean,remove,delete,unused,dangling,space,disk;category=internal;description=Configure how unused Docker images are cleaned up"`
+ MaxImageUploadSize SettingVariable `key:"maxImageUploadSize" meta:"label=Max Image Upload Size;type=number;keywords=upload,size,limit,maximum,image,tar,file,megabytes,mb,storage;category=internal;description=Maximum size in MB for image archive uploads (default: 500)"`
+ DockerHost SettingVariable `key:"dockerHost,public,envOverride" meta:"label=Docker Host;type=text;keywords=docker,host,daemon,socket,unix,remote;category=internal;description=URI for Docker daemon"`
// Security category
AuthLocalEnabled SettingVariable `key:"authLocalEnabled,public" meta:"label=Local Authentication;type=boolean;keywords=local,auth,authentication,username,password,login,credentials;category=security;description=Enable local username/password authentication" catmeta:"id=security;title=Security;icon=shield;url=/settings/security;description=Manage authentication and security settings"`
diff --git a/backend/internal/services/job_service.go b/backend/internal/services/job_service.go
new file mode 100644
index 000000000..ccc2fc58e
--- /dev/null
+++ b/backend/internal/services/job_service.go
@@ -0,0 +1,116 @@
+package services
+
+import (
+ "context"
+ "fmt"
+ "strconv"
+
+ "github.com/getarcaneapp/arcane/backend/internal/config"
+ "github.com/getarcaneapp/arcane/backend/internal/database"
+ "github.com/getarcaneapp/arcane/backend/internal/models"
+ "github.com/getarcaneapp/arcane/types/jobschedule"
+ "gorm.io/gorm"
+)
+
+// JobService manages configuration for background job schedules.
+//
+// Intervals are persisted in the existing settings table as individual keys.
+// After updates, the SettingsService cache is reloaded and a callback can be
+// triggered so the running scheduler can reschedule active jobs.
+//
+// NOTE: This is intentionally separate from SettingsService to keep the API
+// surface job-focused and to centralize schedule validation/rescheduling.
+type JobService struct {
+ db *database.DB
+ settings *SettingsService
+ cfg *config.Config
+
+ OnJobSchedulesChanged func(ctx context.Context)
+}
+
+func NewJobService(db *database.DB, settings *SettingsService, cfg *config.Config) *JobService {
+ return &JobService{db: db, settings: settings, cfg: cfg}
+}
+
+func (s *JobService) GetJobSchedules(ctx context.Context) jobschedule.Config {
+ // Use SettingsService cache for fast reads.
+ return jobschedule.Config{
+ EnvironmentHealthInterval: s.settings.GetIntSetting(ctx, "environmentHealthInterval", 2),
+ EventCleanupInterval: s.settings.GetIntSetting(ctx, "eventCleanupInterval", 360),
+ AnalyticsHeartbeatInterval: s.settings.GetIntSetting(ctx, "analyticsHeartbeatInterval", 1440),
+ }
+}
+
+func (s *JobService) UpdateJobSchedules(ctx context.Context, updates jobschedule.Update) (jobschedule.Config, error) {
+ if s == nil || s.db == nil || s.settings == nil {
+ return jobschedule.Config{}, fmt.Errorf("job service not initialized")
+ }
+ if s.cfg != nil && (s.cfg.UIConfigurationDisabled || s.cfg.AgentMode) {
+ return jobschedule.Config{}, fmt.Errorf("job schedule updates are disabled")
+ }
+
+ current := s.GetJobSchedules(ctx)
+
+ // Validate inputs (minutes)
+ validate := func(name string, v *int, min, max int) error {
+ if v == nil {
+ return nil
+ }
+ if *v < min || *v > max {
+ return fmt.Errorf("%s must be between %d and %d minutes", name, min, max)
+ }
+ return nil
+ }
+
+ // Keep bounds aligned with job-level guardrails.
+ if err := validate("environmentHealthInterval", updates.EnvironmentHealthInterval, 1, 60); err != nil {
+ return jobschedule.Config{}, err
+ }
+ if err := validate("eventCleanupInterval", updates.EventCleanupInterval, 5, 10080); err != nil {
+ return jobschedule.Config{}, err
+ }
+ if err := validate("analyticsHeartbeatInterval", updates.AnalyticsHeartbeatInterval, 60, 43200); err != nil {
+ return jobschedule.Config{}, err
+ }
+
+ changed := false
+ upsert := func(tx *gorm.DB, key string, v *int, currentVal int) error {
+ if v == nil {
+ return nil
+ }
+ if *v == currentVal {
+ return nil
+ }
+ changed = true
+ return tx.Save(&models.SettingVariable{Key: key, Value: strconv.Itoa(*v)}).Error
+ }
+
+ err := s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ if err := upsert(tx, "environmentHealthInterval", updates.EnvironmentHealthInterval, current.EnvironmentHealthInterval); err != nil {
+ return err
+ }
+ if err := upsert(tx, "eventCleanupInterval", updates.EventCleanupInterval, current.EventCleanupInterval); err != nil {
+ return err
+ }
+ if err := upsert(tx, "analyticsHeartbeatInterval", updates.AnalyticsHeartbeatInterval, current.AnalyticsHeartbeatInterval); err != nil {
+ return err
+ }
+ return nil
+ })
+ if err != nil {
+ return jobschedule.Config{}, fmt.Errorf("failed to update job schedules: %w", err)
+ }
+
+ // Refresh settings cache so jobs reading from SettingsService see new values.
+ if changed {
+ if err := s.settings.LoadDatabaseSettings(ctx); err != nil {
+ return jobschedule.Config{}, fmt.Errorf("failed to reload settings after job schedule update: %w", err)
+ }
+
+ if s.OnJobSchedulesChanged != nil {
+ s.OnJobSchedulesChanged(ctx)
+ }
+ }
+
+ return s.GetJobSchedules(ctx), nil
+}
diff --git a/backend/internal/services/settings_search_service.go b/backend/internal/services/settings_search_service.go
index e2291e7f2..691fdc3c1 100644
--- a/backend/internal/services/settings_search_service.go
+++ b/backend/internal/services/settings_search_service.go
@@ -65,7 +65,7 @@ func (s *SettingsSearchService) buildCategoriesFromModel() []category.Category {
keywords := utils.ParseKeywords(metaTag["keywords"])
categoryID := metaTag["category"]
if categoryID == "" {
- categoryID = "general"
+ categoryID = "jobs"
}
// Skip internal category
diff --git a/backend/internal/services/settings_service.go b/backend/internal/services/settings_service.go
index 7be21de7b..dc3789ea5 100644
--- a/backend/internal/services/settings_service.go
+++ b/backend/internal/services/settings_service.go
@@ -77,21 +77,23 @@ func (s *SettingsService) LoadDatabaseSettings(ctx context.Context) (err error)
func (s *SettingsService) getDefaultSettings() *models.Settings {
return &models.Settings{
- ProjectsDirectory: models.SettingVariable{Value: "data/projects"},
- DiskUsagePath: models.SettingVariable{Value: "data/projects"},
- AutoUpdate: models.SettingVariable{Value: "false"},
- AutoUpdateInterval: models.SettingVariable{Value: "1440"},
- PollingEnabled: models.SettingVariable{Value: "true"},
- PollingInterval: models.SettingVariable{Value: "60"},
- AutoInjectEnv: models.SettingVariable{Value: "false"},
- PruneMode: models.SettingVariable{Value: "dangling"},
- BaseServerURL: models.SettingVariable{Value: "http://localhost"},
- EnableGravatar: models.SettingVariable{Value: "true"},
- DefaultShell: models.SettingVariable{Value: "/bin/sh"},
- DockerHost: models.SettingVariable{Value: "unix:///var/run/docker.sock"},
- AuthLocalEnabled: models.SettingVariable{Value: "true"},
- AuthSessionTimeout: models.SettingVariable{Value: "1440"},
- AuthPasswordPolicy: models.SettingVariable{Value: "strong"},
+ ProjectsDirectory: models.SettingVariable{Value: "data/projects"},
+ DiskUsagePath: models.SettingVariable{Value: "data/projects"},
+ AutoUpdate: models.SettingVariable{Value: "false"},
+ AutoUpdateInterval: models.SettingVariable{Value: "1440"},
+ PollingEnabled: models.SettingVariable{Value: "true"},
+ PollingInterval: models.SettingVariable{Value: "60"},
+ EventCleanupInterval: models.SettingVariable{Value: "360"},
+ AnalyticsHeartbeatInterval: models.SettingVariable{Value: "1440"},
+ AutoInjectEnv: models.SettingVariable{Value: "false"},
+ PruneMode: models.SettingVariable{Value: "dangling"},
+ BaseServerURL: models.SettingVariable{Value: "http://localhost"},
+ EnableGravatar: models.SettingVariable{Value: "true"},
+ DefaultShell: models.SettingVariable{Value: "/bin/sh"},
+ DockerHost: models.SettingVariable{Value: "unix:///var/run/docker.sock"},
+ AuthLocalEnabled: models.SettingVariable{Value: "true"},
+ AuthSessionTimeout: models.SettingVariable{Value: "1440"},
+ AuthPasswordPolicy: models.SettingVariable{Value: "strong"},
// AuthOidcConfig DEPRECATED will be removed in a future release
AuthOidcConfig: models.SettingVariable{Value: "{}"},
OidcEnabled: models.SettingVariable{Value: "false"},
diff --git a/cli/go.sum b/cli/go.sum
index f92ad9a1d..6ea5e8060 100644
--- a/cli/go.sum
+++ b/cli/go.sum
@@ -46,8 +46,6 @@ github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=
github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=
-github.com/getarcaneapp/arcane/types v0.0.0-20251219045603-8a9960a2bf04 h1:ufDqwqEr7Ts+gmWo7Rc2ojtUsu3MIC7NzZ2LXhrV/D4=
-github.com/getarcaneapp/arcane/types v0.0.0-20251219045603-8a9960a2bf04/go.mod h1:7Wj+0JnpYq4RQS+otyM6e4zkyJKDC01wxkWPyFCHwZA=
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
diff --git a/cli/internal/types/endpoints.go b/cli/internal/types/endpoints.go
index a8a2f97ee..f7747006c 100644
--- a/cli/internal/types/endpoints.go
+++ b/cli/internal/types/endpoints.go
@@ -104,6 +104,9 @@ type ArcaneApiEndpoints struct {
UpdaterRunEndpoint string
UpdaterHistoryEndpoint string
+ // Job Schedules
+ JobSchedulesEndpoint string
+
// Settings
SettingsEndpoint string
SettingsPublicEndpoint string
@@ -259,6 +262,9 @@ var Endpoints = ArcaneApiEndpoints{
UpdaterRunEndpoint: "/api/environments/%s/updater/run",
UpdaterHistoryEndpoint: "/api/environments/%s/updater/history",
+ // Job Schedules
+ JobSchedulesEndpoint: "/api/job-schedules",
+
// Settings
SettingsEndpoint: "/api/environments/%s/settings",
SettingsPublicEndpoint: "/api/environments/%s/settings/public",
@@ -511,6 +517,9 @@ func (e ArcaneApiEndpoints) UpdaterHistory(envID string) string {
return fmt.Sprintf(e.UpdaterHistoryEndpoint, envID)
}
+// Job schedule endpoints
+func (e ArcaneApiEndpoints) JobSchedules() string { return e.JobSchedulesEndpoint }
+
// Settings endpoints
func (e ArcaneApiEndpoints) Settings(envID string) string {
return fmt.Sprintf(e.SettingsEndpoint, envID)
diff --git a/cli/pkg/jobschedules/cmd.go b/cli/pkg/jobschedules/cmd.go
new file mode 100644
index 000000000..b5148d056
--- /dev/null
+++ b/cli/pkg/jobschedules/cmd.go
@@ -0,0 +1,131 @@
+package jobschedules
+
+import (
+ "encoding/json"
+ "fmt"
+
+ "github.com/getarcaneapp/arcane/cli/internal/client"
+ "github.com/getarcaneapp/arcane/cli/internal/output"
+ "github.com/getarcaneapp/arcane/cli/internal/types"
+ "github.com/getarcaneapp/arcane/types/base"
+ "github.com/getarcaneapp/arcane/types/jobschedule"
+ "github.com/spf13/cobra"
+)
+
+var jsonOutput bool
+
+// JobSchedulesCmd is the parent command for job schedule operations.
+var JobSchedulesCmd = &cobra.Command{
+ Use: "job-schedules",
+ Aliases: []string{"jobs", "job-schedule", "schedules"},
+ Short: "Manage background job schedules",
+}
+
+var getCmd = &cobra.Command{
+ Use: "get",
+ Short: "Get configured job schedule intervals",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ resp, err := c.Get(cmd.Context(), types.Endpoints.JobSchedules())
+ if err != nil {
+ return fmt.Errorf("failed to get job schedules: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var cfg jobschedule.Config
+ if err := json.NewDecoder(resp.Body).Decode(&cfg); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ if jsonOutput {
+ b, err := json.MarshalIndent(cfg, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(b))
+ return nil
+ }
+
+ output.Header("Job Schedules")
+ output.KeyValue("Environment health interval (min)", cfg.EnvironmentHealthInterval)
+ output.KeyValue("Event cleanup interval (min)", cfg.EventCleanupInterval)
+ output.KeyValue("Analytics heartbeat interval (min)", cfg.AnalyticsHeartbeatInterval)
+ return nil
+ },
+}
+
+var (
+ environmentHealthInterval int
+ eventCleanupInterval int
+ analyticsHeartbeatInterval int
+)
+
+var updateCmd = &cobra.Command{
+ Use: "update",
+ Short: "Update job schedule intervals",
+ SilenceUsage: true,
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c, err := client.NewFromConfig()
+ if err != nil {
+ return err
+ }
+
+ var req jobschedule.Update
+ if cmd.Flags().Changed("environment-health-interval") {
+ req.EnvironmentHealthInterval = &environmentHealthInterval
+ }
+ if cmd.Flags().Changed("event-cleanup-interval") {
+ req.EventCleanupInterval = &eventCleanupInterval
+ }
+ if cmd.Flags().Changed("analytics-heartbeat-interval") {
+ req.AnalyticsHeartbeatInterval = &analyticsHeartbeatInterval
+ }
+
+ if req.EnvironmentHealthInterval == nil && req.EventCleanupInterval == nil && req.AnalyticsHeartbeatInterval == nil {
+ return fmt.Errorf("no updates provided (set at least one interval flag)")
+ }
+
+ resp, err := c.Put(cmd.Context(), types.Endpoints.JobSchedules(), req)
+ if err != nil {
+ return fmt.Errorf("failed to update job schedules: %w", err)
+ }
+ defer func() { _ = resp.Body.Close() }()
+
+ var result base.ApiResponse[jobschedule.Config]
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return fmt.Errorf("failed to parse response: %w", err)
+ }
+
+ if jsonOutput {
+ b, err := json.MarshalIndent(result.Data, "", " ")
+ if err != nil {
+ return fmt.Errorf("failed to marshal JSON: %w", err)
+ }
+ fmt.Println(string(b))
+ return nil
+ }
+
+ output.Success("Job schedules updated")
+ output.KeyValue("Environment health interval (min)", result.Data.EnvironmentHealthInterval)
+ output.KeyValue("Event cleanup interval (min)", result.Data.EventCleanupInterval)
+ output.KeyValue("Analytics heartbeat interval (min)", result.Data.AnalyticsHeartbeatInterval)
+ return nil
+ },
+}
+
+func init() {
+ JobSchedulesCmd.AddCommand(getCmd)
+ JobSchedulesCmd.AddCommand(updateCmd)
+
+ getCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+ updateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format")
+
+ updateCmd.Flags().IntVar(&environmentHealthInterval, "environment-health-interval", 0, "Environment health job interval in minutes (1-60)")
+ updateCmd.Flags().IntVar(&eventCleanupInterval, "event-cleanup-interval", 0, "Event cleanup job interval in minutes (5-10080)")
+ updateCmd.Flags().IntVar(&analyticsHeartbeatInterval, "analytics-heartbeat-interval", 0, "Analytics heartbeat job interval in minutes (60-43200)")
+}
diff --git a/cli/pkg/root.go b/cli/pkg/root.go
index 311f6f897..0756cf0e4 100644
--- a/cli/pkg/root.go
+++ b/cli/pkg/root.go
@@ -45,6 +45,7 @@ import (
"github.com/getarcaneapp/arcane/cli/pkg/generate"
"github.com/getarcaneapp/arcane/cli/pkg/images"
"github.com/getarcaneapp/arcane/cli/pkg/imageupdates"
+ "github.com/getarcaneapp/arcane/cli/pkg/jobschedules"
"github.com/getarcaneapp/arcane/cli/pkg/networks"
"github.com/getarcaneapp/arcane/cli/pkg/notifications"
"github.com/getarcaneapp/arcane/cli/pkg/projects"
@@ -126,6 +127,7 @@ func init() {
rootCmd.AddCommand(registries.RegistriesCmd)
rootCmd.AddCommand(templates.TemplatesCmd)
rootCmd.AddCommand(settings.SettingsCmd)
+ rootCmd.AddCommand(jobschedules.JobSchedulesCmd)
rootCmd.AddCommand(notifications.NotificationsCmd)
rootCmd.AddCommand(imageupdates.ImageUpdatesCmd)
rootCmd.AddCommand(system.SystemCmd)
diff --git a/frontend/messages/en.json b/frontend/messages/en.json
index 20cb2d0ea..301c5a703 100644
--- a/frontend/messages/en.json
+++ b/frontend/messages/en.json
@@ -835,6 +835,20 @@
"security_settings_saved": "Settings saved successfully.",
"security_local_enabled_info": "Local Authentication enabled to ensure at least one provider is active.",
"security_settings_save_failed": "Failed to save security settings",
+ "_comment_settings_jobs": "=== SETTINGS - JOBS ===",
+ "jobs_title": "Job Schedules",
+ "jobs_description": "Configure how often Arcane background jobs run. Changes apply immediately.",
+ "jobs_monitoring_heading": "Monitoring",
+ "jobs_maintenance_heading": "Maintenance",
+ "jobs_telemetry_heading": "Telemetry",
+ "jobs_event_cleanup_title": "Event Cleanup",
+ "jobs_event_cleanup_description": "How often Arcane deletes events older than 36 hours",
+ "jobs_event_cleanup_interval_label": "Event Cleanup Interval (minutes)",
+ "jobs_event_cleanup_interval_help": "Run every 5–10080 minutes",
+ "jobs_analytics_title": "Analytics Heartbeat",
+ "jobs_analytics_description": "Only runs in production, and only if analytics are enabled",
+ "jobs_analytics_interval_label": "Analytics Heartbeat Interval (minutes)",
+ "jobs_analytics_interval_help": "Minimum 60 minutes",
"_comment_settings_docker": "=== SETTINGS - DOCKER ===",
"docker_title": "Docker",
"docker_description": "Configure Docker automation behavior and settings.",
diff --git a/frontend/src/lib/config/navigation-config.ts b/frontend/src/lib/config/navigation-config.ts
index e537e4d13..e19126d83 100644
--- a/frontend/src/lib/config/navigation-config.ts
+++ b/frontend/src/lib/config/navigation-config.ts
@@ -14,7 +14,8 @@ import {
NetworksIcon,
VolumesIcon,
EventsIcon,
- SettingsIcon
+ SettingsIcon,
+ JobsIcon
} from '$lib/icons';
import { m } from '$lib/paraglide/messages';
@@ -50,12 +51,12 @@ export const navigationItems: Record<string, NavigationItem[]> = {
url: '/settings',
icon: SettingsIcon,
items: [
- { title: m.general_title(), url: '/settings/general', icon: SettingsIcon },
+ { title: m.api_key_page_title(), url: '/settings/api-keys', icon: ApiKeyIcon },
{ title: m.appearance_title(), url: '/settings/appearance', icon: ApperanceIcon },
- { title: m.security_title(), url: '/settings/security', icon: SecurityIcon },
- { title: m.users_title(), url: '/settings/users', icon: UsersIcon },
+ { title: m.jobs_title(), url: '/settings/jobs', icon: JobsIcon },
{ title: m.notifications_title(), url: '/settings/notifications', icon: NotificationsIcon },
- { title: m.api_key_page_title(), url: '/settings/api-keys', icon: ApiKeyIcon }
+ { title: m.security_title(), url: '/settings/security', icon: SecurityIcon },
+ { title: m.users_title(), url: '/settings/users', icon: UsersIcon }
]
}
]
diff --git a/frontend/src/lib/icons/index.ts b/frontend/src/lib/icons/index.ts
index c48f62457..0b76de821 100644
--- a/frontend/src/lib/icons/index.ts
+++ b/frontend/src/lib/icons/index.ts
@@ -103,3 +103,4 @@ export { default as VolumeUnusedIcon } from 'virtual:icons/clarity/hard-disk-sol
export { default as VolumeUsedIcon } from 'virtual:icons/clarity/hard-disk-solid-badged';
export { default as OpenIdIcon } from 'virtual:icons/simple-icons/openid';
export { default as LoginIcon } from 'virtual:icons/solar/login-3-linear';
+export { default as JobsIcon } from 'virtual:icons/solar/alarm-linear';
diff --git a/frontend/src/lib/services/job-schedule-service.ts b/frontend/src/lib/services/job-schedule-service.ts
new file mode 100644
index 000000000..59a62195a
--- /dev/null
+++ b/frontend/src/lib/services/job-schedule-service.ts
@@ -0,0 +1,15 @@
+import BaseAPIService from './api-service';
+import type { JobSchedules, JobSchedulesUpdate } from '$lib/types/job-schedule.type';
+
+class JobScheduleService extends BaseAPIService {
+ async getJobSchedules(): Promise<JobSchedules> {
+ return this.handleResponse(this.api.get('/job-schedules'));
+ }
+
+ async updateJobSchedules(update: JobSchedulesUpdate): Promise<JobSchedules> {
+ return this.handleResponse(this.api.put('/job-schedules', update));
+ }
+}
+
+export const jobScheduleService = new JobScheduleService();
+export default JobScheduleService;
diff --git a/frontend/src/lib/types/job-schedule.type.ts b/frontend/src/lib/types/job-schedule.type.ts
new file mode 100644
index 000000000..7619168d7
--- /dev/null
+++ b/frontend/src/lib/types/job-schedule.type.ts
@@ -0,0 +1,7 @@
+export type JobSchedules = {
+ environmentHealthInterval: number;
+ eventCleanupInterval: number;
+ analyticsHeartbeatInterval: number;
+};
+
+export type JobSchedulesUpdate = Partial<JobSchedules>;
diff --git a/frontend/src/routes/(app)/settings/+layout.svelte b/frontend/src/routes/(app)/settings/+layout.svelte
index 4795c764b..1d85849a8 100644
--- a/frontend/src/routes/(app)/settings/+layout.svelte
+++ b/frontend/src/routes/(app)/settings/+layout.svelte
@@ -131,8 +131,8 @@
let pageTitle = $derived(() => {
switch (currentPageName) {
- case 'general':
- return m.general_title();
+ case 'jobs':
+ return m.jobs_title();
case 'docker':
return m.docker_title();
case 'security':
diff --git a/frontend/src/routes/(app)/settings/+page.svelte b/frontend/src/routes/(app)/settings/+page.svelte
index 7695177a9..195bbed00 100644
--- a/frontend/src/routes/(app)/settings/+page.svelte
+++ b/frontend/src/routes/(app)/settings/+page.svelte
@@ -11,7 +11,8 @@
DockerBrandIcon,
ApiKeyIcon,
ApperanceIcon,
- CloseIcon
+ CloseIcon,
+ JobsIcon
} from '$lib/icons';
import { ArcaneButton } from '$lib/components/arcane-button/index.js';
import { Card } from '$lib/components/ui/card';
@@ -37,7 +38,8 @@
appearance: ApperanceIcon,
bell: NotificationsIcon,
user: UserIcon,
- apikey: ApiKeyIcon
+ apikey: ApiKeyIcon,
+ jobs: JobsIcon
};
onMount(async () => {
diff --git a/frontend/src/routes/(app)/settings/general/+page.svelte b/frontend/src/routes/(app)/settings/general/+page.svelte
deleted file mode 100644
index b73f2a227..000000000
--- a/frontend/src/routes/(app)/settings/general/+page.svelte
+++ /dev/null
@@ -1,67 +0,0 @@
-<script lang="ts">
- import { z } from 'zod/v4';
- import { m } from '$lib/paraglide/messages';
- import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
- import settingsStore from '$lib/stores/config-store';
- import { SettingsIcon } from '$lib/icons';
- import { SettingsPageLayout } from '$lib/layouts';
- import { createSettingsForm } from '$lib/utils/settings-form.util';
- import { Separator } from '$lib/components/ui/separator';
- import { Label } from '$lib/components/ui/label';
-
- let { data } = $props();
-
- const currentSettings = $derived($settingsStore || data.settings!);
- const isReadOnly = $derived.by(() => $settingsStore?.uiConfigDisabled);
-
- const formSchema = z.object({
- environmentHealthInterval: z.coerce.number().int().min(1).max(60)
- });
-
- let { formInputs } = $derived(
- createSettingsForm({
- schema: formSchema,
- currentSettings,
- getCurrentSettings: () => $settingsStore || data.settings!,
- successMessage: m.general_settings_saved()
- })
- );
-</script>
-
-<SettingsPageLayout
- title={m.general_title()}
- description={m.general_description()}
- icon={SettingsIcon}
- pageType="form"
- showReadOnlyTag={isReadOnly}
->
- {#snippet mainContent()}
- <fieldset disabled={isReadOnly} class="relative space-y-8">
- <!-- System Configuration Section -->
- <div class="space-y-4">
- <h3 class="text-lg font-medium">System Configuration</h3>
- <div class="bg-card rounded-lg border shadow-sm">
- <div class="space-y-6 p-6">
- <!-- Health Check -->
- <div class="grid gap-4 md:grid-cols-[1fr_1.5fr] md:gap-8">
- <div>
- <Label class="text-base">{m.environments_health_check_title()}</Label>
- <p class="text-muted-foreground mt-1 text-sm">{m.environments_health_check_description()}</p>
- </div>
- <div class="max-w-xs">
- <TextInputWithLabel
- bind:value={$formInputs.environmentHealthInterval.value}
- error={$formInputs.environmentHealthInterval.error}
- label={m.environments_health_check_interval_label()}
- placeholder="2"
- helpText={m.environments_health_check_interval_description()}
- type="number"
- />
- </div>
- </div>
- </div>
- </div>
- </div>
- </fieldset>
- {/snippet}
-</SettingsPageLayout>
diff --git a/frontend/src/routes/(app)/settings/jobs/+page.svelte b/frontend/src/routes/(app)/settings/jobs/+page.svelte
new file mode 100644
index 000000000..b0bb4b76e
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/jobs/+page.svelte
@@ -0,0 +1,192 @@
+<script lang="ts">
+ import { getContext } from 'svelte';
+ import { untrack } from 'svelte';
+ import { toast } from 'svelte-sonner';
+ import { z } from 'zod/v4';
+ import { m } from '$lib/paraglide/messages';
+ import TextInputWithLabel from '$lib/components/form/text-input-with-label.svelte';
+ import settingsStore from '$lib/stores/config-store';
+ import { JobsIcon } from '$lib/icons';
+ import { SettingsPageLayout } from '$lib/layouts';
+ import { Label } from '$lib/components/ui/label';
+ import { createForm } from '$lib/utils/form.utils';
+ import { tryCatch } from '$lib/utils/try-catch';
+ import { jobScheduleService } from '$lib/services/job-schedule-service';
+ import type { JobSchedules } from '$lib/types/job-schedule.type';
+
+ let { data } = $props();
+
+ const isReadOnly = $derived.by(() => $settingsStore?.uiConfigDisabled);
+ let isLoading = $state(false);
+
+ // Track the last saved schedules separately so we can compute hasChanges and reset.
+ let savedSchedules = $state<JobSchedules>(untrack(() => data.jobSchedules));
+
+ const formSchema = z.object({
+ environmentHealthInterval: z.coerce.number().int().min(1).max(60),
+ eventCleanupInterval: z.coerce.number().int().min(5).max(10080),
+ analyticsHeartbeatInterval: z.coerce.number().int().min(60).max(43200)
+ });
+
+ const form = createForm(
+ formSchema,
+ untrack(() => savedSchedules)
+ );
+ const formInputs = form.inputs;
+
+ const hasChanges = $derived.by(() => {
+ const inputs = $formInputs;
+ return (
+ inputs.environmentHealthInterval.value !== savedSchedules.environmentHealthInterval ||
+ inputs.eventCleanupInterval.value !== savedSchedules.eventCleanupInterval ||
+ inputs.analyticsHeartbeatInterval.value !== savedSchedules.analyticsHeartbeatInterval
+ );
+ });
+
+ // Integrate with Settings layout Save/Reset buttons via context.
+ type SettingsFormState = {
+ hasChanges: boolean;
+ isLoading: boolean;
+ saveFunction: (() => Promise<void>) | null;
+ resetFunction: (() => void) | null;
+ };
+ let formState: SettingsFormState | null = null;
+ try {
+ formState = getContext('settingsFormState') as SettingsFormState;
+ } catch {
+ // Context not available (shouldn't happen in settings routes)
+ }
+
+ function resetForm() {
+ formInputs.update((inputs) => {
+ inputs.environmentHealthInterval.value = savedSchedules.environmentHealthInterval;
+ inputs.environmentHealthInterval.error = null;
+ inputs.eventCleanupInterval.value = savedSchedules.eventCleanupInterval;
+ inputs.eventCleanupInterval.error = null;
+ inputs.analyticsHeartbeatInterval.value = savedSchedules.analyticsHeartbeatInterval;
+ inputs.analyticsHeartbeatInterval.error = null;
+ return inputs;
+ });
+ }
+
+ async function save() {
+ if (isReadOnly) {
+ return;
+ }
+
+ const values = form.validate();
+ if (!values) {
+ toast.error('Please check the form for errors');
+ return;
+ }
+
+ isLoading = true;
+ const result = await tryCatch(jobScheduleService.updateJobSchedules(values));
+ isLoading = false;
+
+ if (result.error) {
+ console.error('Failed to update job schedules:', result.error);
+ toast.error(result.error.message || 'Failed to update job schedules');
+ return;
+ }
+
+ savedSchedules = result.data;
+ resetForm();
+ toast.success(m.security_settings_saved());
+ }
+
+ $effect(() => {
+ if (!formState) return;
+ formState.hasChanges = hasChanges;
+ formState.isLoading = isLoading;
+ formState.saveFunction = save;
+ formState.resetFunction = resetForm;
+ });
+</script>
+
+<SettingsPageLayout
+ title={m.jobs_title()}
+ description={m.jobs_description()}
+ icon={JobsIcon}
+ pageType="form"
+ showReadOnlyTag={isReadOnly}
+>
+ {#snippet mainContent()}
+ <fieldset disabled={isReadOnly || isLoading} class="relative space-y-8">
+ <!-- Monitoring -->
+ <div class="space-y-4">
+ <h3 class="text-lg font-medium">{m.jobs_monitoring_heading()}</h3>
+ <div class="bg-card rounded-lg border shadow-sm">
+ <div class="space-y-6 p-6">
+ <div class="grid gap-4 md:grid-cols-[1fr_1.5fr] md:gap-8">
+ <div>
+ <Label class="text-base">{m.environments_health_check_title()}</Label>
+ <p class="text-muted-foreground mt-1 text-sm">{m.environments_health_check_description()}</p>
+ </div>
+ <div class="max-w-xs">
+ <TextInputWithLabel
+ bind:value={$formInputs.environmentHealthInterval.value}
+ error={$formInputs.environmentHealthInterval.error}
+ label={m.environments_health_check_interval_label()}
+ placeholder="2"
+ helpText={m.environments_health_check_interval_description()}
+ type="number"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Maintenance -->
+ <div class="space-y-4">
+ <h3 class="text-lg font-medium">{m.jobs_maintenance_heading()}</h3>
+ <div class="bg-card rounded-lg border shadow-sm">
+ <div class="space-y-6 p-6">
+ <div class="grid gap-4 md:grid-cols-[1fr_1.5fr] md:gap-8">
+ <div>
+ <Label class="text-base">{m.jobs_event_cleanup_title()}</Label>
+ <p class="text-muted-foreground mt-1 text-sm">{m.jobs_event_cleanup_description()}</p>
+ </div>
+ <div class="max-w-xs">
+ <TextInputWithLabel
+ bind:value={$formInputs.eventCleanupInterval.value}
+ error={$formInputs.eventCleanupInterval.error}
+ label={m.jobs_event_cleanup_interval_label()}
+ placeholder="360"
+ helpText={m.jobs_event_cleanup_interval_help()}
+ type="number"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ <!-- Telemetry -->
+ <div class="space-y-4">
+ <h3 class="text-lg font-medium">{m.jobs_telemetry_heading()}</h3>
+ <div class="bg-card rounded-lg border shadow-sm">
+ <div class="space-y-6 p-6">
+ <div class="grid gap-4 md:grid-cols-[1fr_1.5fr] md:gap-8">
+ <div>
+ <Label class="text-base">{m.jobs_analytics_title()}</Label>
+ <p class="text-muted-foreground mt-1 text-sm">{m.jobs_analytics_description()}</p>
+ </div>
+ <div class="max-w-xs">
+ <TextInputWithLabel
+ bind:value={$formInputs.analyticsHeartbeatInterval.value}
+ error={$formInputs.analyticsHeartbeatInterval.error}
+ label={m.jobs_analytics_interval_label()}
+ placeholder="1440"
+ helpText={m.jobs_analytics_interval_help()}
+ type="number"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ </div>
+ </fieldset>
+ {/snippet}
+</SettingsPageLayout>
diff --git a/frontend/src/routes/(app)/settings/jobs/+page.ts b/frontend/src/routes/(app)/settings/jobs/+page.ts
new file mode 100644
index 000000000..ce7e9c024
--- /dev/null
+++ b/frontend/src/routes/(app)/settings/jobs/+page.ts
@@ -0,0 +1,12 @@
+import type { PageLoad } from './$types';
+import { jobScheduleService } from '$lib/services/job-schedule-service';
+
+export const load: PageLoad = async () => {
+ try {
+ const jobSchedules = await jobScheduleService.getJobSchedules();
+ return { jobSchedules };
+ } catch (error) {
+ console.error('Failed to load job schedules:', error);
+ throw error;
+ }
+};
diff --git a/go.work.sum b/go.work.sum
index 398f933fc..e07dc5984 100644
--- a/go.work.sum
+++ b/go.work.sum
@@ -228,6 +228,7 @@ github.com/fsouza/fake-gcs-server v1.17.0 h1:OeH75kBZcZa3ZE+zz/mFdJ2btt9FgqfjI7g
github.com/fsouza/fake-gcs-server v1.17.0/go.mod h1:D1rTE4YCyHFNa99oyJJ5HyclvN/0uQR+pM/VdlL83bw=
github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM=
github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ=
+github.com/getarcaneapp/arcane/types v0.0.0-20251219045603-8a9960a2bf04/go.mod h1:7Wj+0JnpYq4RQS+otyM6e4zkyJKDC01wxkWPyFCHwZA=
github.com/go-chi/chi/v5 v5.2.2 h1:CMwsvRVTbXVytCk1Wd72Zy1LAsAh9GxMmSNWLHCG618=
github.com/go-chi/chi/v5 v5.2.2/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
github.com/go-co-op/gocron/v2 v2.18.2/go.mod h1:Zii6he+Zfgy5W9B+JKk/KwejFOW0kZTFvHtwIpR4aBI=
diff --git a/types/jobschedule/jobschedule.go b/types/jobschedule/jobschedule.go
new file mode 100644
index 000000000..0451f9c34
--- /dev/null
+++ b/types/jobschedule/jobschedule.go
@@ -0,0 +1,20 @@
+package jobschedule
+
+// Config represents the configured intervals (in minutes) for Arcane background jobs.
+//
+// All fields are in minutes.
+// This makes conversion to time.Duration straightforward in the backend.
+type Config struct {
+ EnvironmentHealthInterval int `json:"environmentHealthInterval"`
+ EventCleanupInterval int `json:"eventCleanupInterval"`
+ AnalyticsHeartbeatInterval int `json:"analyticsHeartbeatInterval"`
+}
+
+// Update is used to update job schedule intervals (in minutes).
+//
+// Any nil field is ignored.
+type Update struct {
+ EnvironmentHealthInterval *int `json:"environmentHealthInterval,omitempty"`
+ EventCleanupInterval *int `json:"eventCleanupInterval,omitempty"`
+ AnalyticsHeartbeatInterval *int `json:"analyticsHeartbeatInterval,omitempty"`
+}