Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FEATURE (intervals): Add cron intervals for backups

Rostislav Duginf14739a1fb14
diff --git a/README.md b/README.md
index b73048ac..38118115 100644
--- a/README.md
+++ b/README.md
@@ -38,14 +38,14 @@
### πŸ”„ **Scheduled Backups**
-- **Flexible scheduling**: hourly, daily, weekly, monthly
+- **Flexible scheduling**: hourly, daily, weekly, monthly or cron
- **Precise timing**: run backups at specific times (e.g., 4 AM during low traffic)
- **Smart compression**: 4-8x space savings with balanced compression (~20% overhead)
### πŸ—„οΈ **Multiple Storage Destinations** <a href="https://postgresus.com/storages">(view supported)</a>
- **Local storage**: Keep backups on your VPS/server
-- **Cloud storage**: S3, Cloudflare R2, Google Drive, NAS, Dropbox and more
+- **Cloud storage**: S3, Cloudflare R2, Google Drive, NAS, Dropbox, SFTP, Rclone and more
- **Secure**: All data stays under your control
### πŸ“± **Smart Notifications** <a href="https://postgresus.com/notifiers">(view supported)</a>
@@ -212,7 +212,7 @@ For more options (NodePort, TLS, HTTPRoute for Gateway API), see the [Helm chart
1. **Access the dashboard**: Navigate to `http://localhost:4005`
2. **Add first DB for backup**: Click "New Database" and follow the setup wizard
-3. **Configure schedule**: Choose from hourly, daily, weekly or monthly intervals
+3. **Configure schedule**: Choose from hourly, daily, weekly, monthly or cron intervals
4. **Set database connection**: Enter your PostgreSQL credentials and connection details
5. **Choose storage**: Select where to store your backups (local, S3, Google Drive, etc.)
6. **Add notifications** (optional): Configure email, Telegram, Slack, or webhook notifications
diff --git a/backend/go.mod b/backend/go.mod
index a82ef508..8fcfa6c0 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -155,6 +155,7 @@ require (
github.com/putdotio/go-putio/putio v0.0.0-20200123120452-16d982cac2b8 // indirect
github.com/relvacode/iso8601 v1.7.0 // indirect
github.com/rfjakob/eme v1.1.2 // indirect
+ github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 // indirect
github.com/samber/lo v1.52.0 // indirect
github.com/sirupsen/logrus v1.9.4-0.20230606125235-dd1b4c2e81af // indirect
diff --git a/backend/go.sum b/backend/go.sum
index 31817834..90dbc578 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -588,6 +588,8 @@ github.com/relvacode/iso8601 v1.7.0 h1:BXy+V60stMP6cpswc+a93Mq3e65PfXCgDFfhvNNGr
github.com/relvacode/iso8601 v1.7.0/go.mod h1:FlNp+jz+TXpyRqgmM7tnzHHzBnz776kmAH2h3sZCn0I=
github.com/rfjakob/eme v1.1.2 h1:SxziR8msSOElPayZNFfQw4Tjx/Sbaeeh3eRvrHVMUs4=
github.com/rfjakob/eme v1.1.2/go.mod h1:cVvpasglm/G3ngEfcfT/Wt0GwhkuO32pf/poW6Nyk1k=
+github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
+github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
diff --git a/backend/internal/features/intervals/enums.go b/backend/internal/features/intervals/enums.go
index e4efcec0..9e9f3882 100644
--- a/backend/internal/features/intervals/enums.go
+++ b/backend/internal/features/intervals/enums.go
@@ -7,4 +7,5 @@ const (
IntervalDaily IntervalType = "DAILY"
IntervalWeekly IntervalType = "WEEKLY"
IntervalMonthly IntervalType = "MONTHLY"
+ IntervalCron IntervalType = "CRON"
)
diff --git a/backend/internal/features/intervals/model.go b/backend/internal/features/intervals/model.go
index 91f21126..921aa967 100644
--- a/backend/internal/features/intervals/model.go
+++ b/backend/internal/features/intervals/model.go
@@ -5,6 +5,7 @@ import (
"time"
"github.com/google/uuid"
+ "github.com/robfig/cron/v3"
"gorm.io/gorm"
)
@@ -12,11 +13,13 @@ type Interval struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;default:gen_random_uuid()"`
Interval IntervalType `json:"interval" gorm:"type:text;not null"`
- TimeOfDay *string `json:"timeOfDay" gorm:"type:text;"`
+ TimeOfDay *string `json:"timeOfDay" gorm:"type:text;"`
// only for WEEKLY
- Weekday *int `json:"weekday,omitempty" gorm:"type:int"`
+ Weekday *int `json:"weekday,omitempty" gorm:"type:int"`
// only for MONTHLY
- DayOfMonth *int `json:"dayOfMonth,omitempty" gorm:"type:int"`
+ DayOfMonth *int `json:"dayOfMonth,omitempty" gorm:"type:int"`
+ // only for CRON
+ CronExpression *string `json:"cronExpression,omitempty" gorm:"type:text"`
}
func (i *Interval) BeforeSave(tx *gorm.DB) error {
@@ -40,6 +43,16 @@ func (i *Interval) Validate() error {
return errors.New("day of month is required for monthly intervals")
}
+ // for cron interval cron expression is required and must be valid
+ if i.Interval == IntervalCron {
+ if i.CronExpression == nil || *i.CronExpression == "" {
+ return errors.New("cron expression is required for cron intervals")
+ }
+ if err := i.validateCronExpression(*i.CronExpression); err != nil {
+ return err
+ }
+ }
+
return nil
}
@@ -59,6 +72,8 @@ func (i *Interval) ShouldTriggerBackup(now time.Time, lastBackupTime *time.Time)
return i.shouldTriggerWeekly(now, *lastBackupTime)
case IntervalMonthly:
return i.shouldTriggerMonthly(now, *lastBackupTime)
+ case IntervalCron:
+ return i.shouldTriggerCron(now, *lastBackupTime)
default:
return false
}
@@ -66,11 +81,12 @@ func (i *Interval) ShouldTriggerBackup(now time.Time, lastBackupTime *time.Time)
func (i *Interval) Copy() *Interval {
return &Interval{
- ID: uuid.Nil,
- Interval: i.Interval,
- TimeOfDay: i.TimeOfDay,
- Weekday: i.Weekday,
- DayOfMonth: i.DayOfMonth,
+ ID: uuid.Nil,
+ Interval: i.Interval,
+ TimeOfDay: i.TimeOfDay,
+ Weekday: i.Weekday,
+ DayOfMonth: i.DayOfMonth,
+ CronExpression: i.CronExpression,
}
}
@@ -204,3 +220,31 @@ func getStartOfWeek(t time.Time) time.Time {
func getStartOfMonth(t time.Time) time.Time {
return time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location())
}
+
+// cron trigger: check if we've passed a scheduled cron time since last backup
+func (i *Interval) shouldTriggerCron(now, lastBackup time.Time) bool {
+ if i.CronExpression == nil || *i.CronExpression == "" {
+ return false
+ }
+
+ parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
+ schedule, err := parser.Parse(*i.CronExpression)
+ if err != nil {
+ return false
+ }
+
+ // Find the next scheduled time after the last backup
+ nextAfterLastBackup := schedule.Next(lastBackup)
+
+ // If we're at or past that next scheduled time, trigger
+ return now.After(nextAfterLastBackup) || now.Equal(nextAfterLastBackup)
+}
+
+func (i *Interval) validateCronExpression(expr string) error {
+ parser := cron.NewParser(cron.Minute | cron.Hour | cron.Dom | cron.Month | cron.Dow)
+ _, err := parser.Parse(expr)
+ if err != nil {
+ return errors.New("invalid cron expression: " + err.Error())
+ }
+ return nil
+}
diff --git a/backend/internal/features/intervals/model_test.go b/backend/internal/features/intervals/model_test.go
index 81b69eaa..b5197d5f 100644
--- a/backend/internal/features/intervals/model_test.go
+++ b/backend/internal/features/intervals/model_test.go
@@ -457,6 +457,144 @@ func TestInterval_ShouldTriggerBackup_Monthly(t *testing.T) {
)
}
+func TestInterval_ShouldTriggerBackup_Cron(t *testing.T) {
+ cronExpr := "0 2 * * *" // Daily at 2:00 AM
+ interval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ CronExpression: &cronExpr,
+ }
+
+ t.Run("No previous backup: Trigger backup immediately", func(t *testing.T) {
+ now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)
+ should := interval.ShouldTriggerBackup(now, nil)
+ assert.True(t, should)
+ })
+
+ t.Run("Before scheduled cron time: Do not trigger backup", func(t *testing.T) {
+ now := time.Date(2024, 1, 15, 1, 59, 0, 0, time.UTC)
+ lastBackup := time.Date(2024, 1, 14, 2, 0, 0, 0, time.UTC) // Yesterday at 2 AM
+ should := interval.ShouldTriggerBackup(now, &lastBackup)
+ assert.False(t, should)
+ })
+
+ t.Run("Exactly at scheduled cron time: Trigger backup", func(t *testing.T) {
+ now := time.Date(2024, 1, 15, 2, 0, 0, 0, time.UTC)
+ lastBackup := time.Date(2024, 1, 14, 2, 0, 0, 0, time.UTC) // Yesterday at 2 AM
+ should := interval.ShouldTriggerBackup(now, &lastBackup)
+ assert.True(t, should)
+ })
+
+ t.Run("After scheduled cron time: Trigger backup", func(t *testing.T) {
+ now := time.Date(2024, 1, 15, 3, 0, 0, 0, time.UTC)
+ lastBackup := time.Date(2024, 1, 14, 2, 0, 0, 0, time.UTC) // Yesterday at 2 AM
+ should := interval.ShouldTriggerBackup(now, &lastBackup)
+ assert.True(t, should)
+ })
+
+ t.Run("Backup already done after scheduled time: Do not trigger again", func(t *testing.T) {
+ now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)
+ lastBackup := time.Date(2024, 1, 15, 2, 5, 0, 0, time.UTC) // Today at 2:05 AM
+ should := interval.ShouldTriggerBackup(now, &lastBackup)
+ assert.False(t, should)
+ })
+
+ t.Run("Weekly cron expression: 0 3 * * 1 (Monday at 3 AM)", func(t *testing.T) {
+ weeklyCron := "0 3 * * 1" // Every Monday at 3 AM
+ weeklyInterval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ CronExpression: &weeklyCron,
+ }
+
+ // Monday Jan 15, 2024 at 3:00 AM
+ monday := time.Date(2024, 1, 15, 3, 0, 0, 0, time.UTC)
+ // Last backup was previous Monday
+ lastBackup := time.Date(2024, 1, 8, 3, 0, 0, 0, time.UTC)
+
+ should := weeklyInterval.ShouldTriggerBackup(monday, &lastBackup)
+ assert.True(t, should)
+ })
+
+ t.Run("Complex cron expression: 30 4 1,15 * * (1st and 15th at 4:30 AM)", func(t *testing.T) {
+ complexCron := "30 4 1,15 * *" // 1st and 15th of each month at 4:30 AM
+ complexInterval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ CronExpression: &complexCron,
+ }
+
+ // Jan 15, 2024 at 4:30 AM
+ now := time.Date(2024, 1, 15, 4, 30, 0, 0, time.UTC)
+ // Last backup was Jan 1
+ lastBackup := time.Date(2024, 1, 1, 4, 30, 0, 0, time.UTC)
+
+ should := complexInterval.ShouldTriggerBackup(now, &lastBackup)
+ assert.True(t, should)
+ })
+
+ t.Run("Every 6 hours cron expression: 0 */6 * * *", func(t *testing.T) {
+ sixHourlyCron := "0 */6 * * *" // Every 6 hours (0:00, 6:00, 12:00, 18:00)
+ sixHourlyInterval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ CronExpression: &sixHourlyCron,
+ }
+
+ // 12:00 - next trigger after 6:00
+ now := time.Date(2024, 1, 15, 12, 0, 0, 0, time.UTC)
+ // Last backup was at 6:00
+ lastBackup := time.Date(2024, 1, 15, 6, 0, 0, 0, time.UTC)
+
+ should := sixHourlyInterval.ShouldTriggerBackup(now, &lastBackup)
+ assert.True(t, should)
+ })
+
+ t.Run("Invalid cron expression returns false", func(t *testing.T) {
+ invalidCron := "invalid cron"
+ invalidInterval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ CronExpression: &invalidCron,
+ }
+
+ now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)
+ lastBackup := time.Date(2024, 1, 14, 10, 0, 0, 0, time.UTC)
+
+ should := invalidInterval.ShouldTriggerBackup(now, &lastBackup)
+ assert.False(t, should)
+ })
+
+ t.Run("Empty cron expression returns false", func(t *testing.T) {
+ emptyCron := ""
+ emptyInterval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ CronExpression: &emptyCron,
+ }
+
+ now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)
+ lastBackup := time.Date(2024, 1, 14, 10, 0, 0, 0, time.UTC)
+
+ should := emptyInterval.ShouldTriggerBackup(now, &lastBackup)
+ assert.False(t, should)
+ })
+
+ t.Run("Nil cron expression returns false", func(t *testing.T) {
+ nilInterval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ CronExpression: nil,
+ }
+
+ now := time.Date(2024, 1, 15, 10, 0, 0, 0, time.UTC)
+ lastBackup := time.Date(2024, 1, 14, 10, 0, 0, 0, time.UTC)
+
+ should := nilInterval.ShouldTriggerBackup(now, &lastBackup)
+ assert.False(t, should)
+ })
+}
+
func TestInterval_Validate(t *testing.T) {
t.Run("Daily interval requires time of day", func(t *testing.T) {
interval := &Interval{
@@ -526,4 +664,60 @@ func TestInterval_Validate(t *testing.T) {
err := interval.Validate()
assert.NoError(t, err)
})
+
+ t.Run("Cron interval requires cron expression", func(t *testing.T) {
+ interval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ }
+ err := interval.Validate()
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), "cron expression is required")
+ })
+
+ t.Run("Cron interval with empty expression is invalid", func(t *testing.T) {
+ emptyCron := ""
+ interval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ CronExpression: &emptyCron,
+ }
+ err := interval.Validate()
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), "cron expression is required")
+ })
+
+ t.Run("Cron interval with invalid expression is invalid", func(t *testing.T) {
+ invalidCron := "invalid cron"
+ interval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ CronExpression: &invalidCron,
+ }
+ err := interval.Validate()
+ assert.Error(t, err)
+ assert.Contains(t, err.Error(), "invalid cron expression")
+ })
+
+ t.Run("Valid cron interval with daily expression", func(t *testing.T) {
+ cronExpr := "0 2 * * *" // Daily at 2 AM
+ interval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ CronExpression: &cronExpr,
+ }
+ err := interval.Validate()
+ assert.NoError(t, err)
+ })
+
+ t.Run("Valid cron interval with complex expression", func(t *testing.T) {
+ cronExpr := "30 4 1,15 * *" // 1st and 15th of each month at 4:30 AM
+ interval := &Interval{
+ ID: uuid.New(),
+ Interval: IntervalCron,
+ CronExpression: &cronExpr,
+ }
+ err := interval.Validate()
+ assert.NoError(t, err)
+ })
}
diff --git a/backend/migrations/20251219230000_add_cron_expression.sql b/backend/migrations/20251219230000_add_cron_expression.sql
new file mode 100644
index 00000000..bbe09af3
--- /dev/null
+++ b/backend/migrations/20251219230000_add_cron_expression.sql
@@ -0,0 +1,5 @@
+-- +goose Up
+ALTER TABLE intervals ADD COLUMN cron_expression TEXT;
+
+-- +goose Down
+ALTER TABLE intervals DROP COLUMN cron_expression;
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index b80facf4..af8c8268 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -10,6 +10,7 @@
"dependencies": {
"@tailwindcss/vite": "^4.1.7",
"antd": "^5.25.1",
+ "cron-parser": "^5.4.0",
"dayjs": "^1.11.13",
"react": "^19.1.0",
"react-dom": "^19.1.0",
@@ -3138,6 +3139,18 @@
"toggle-selection": "^1.0.6"
}
},
+ "node_modules/cron-parser": {
+ "version": "5.4.0",
+ "resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-5.4.0.tgz",
+ "integrity": "sha512-HxYB8vTvnQFx4dLsZpGRa0uHp6X3qIzS3ZJgJ9v6l/5TJMgeWQbLkR5yiJ5hOxGbc9+jCADDnydIe15ReLZnJA==",
+ "license": "MIT",
+ "dependencies": {
+ "luxon": "^3.7.1"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -5463,6 +5476,15 @@
"yallist": "^3.0.2"
}
},
+ "node_modules/luxon": {
+ "version": "3.7.2",
+ "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz",
+ "integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
"node_modules/magic-string": {
"version": "0.30.17",
"resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.17.tgz",
diff --git a/frontend/package.json b/frontend/package.json
index 5e1ca7af..9a97409f 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -15,6 +15,7 @@
"dependencies": {
"@tailwindcss/vite": "^4.1.7",
"antd": "^5.25.1",
+ "cron-parser": "^5.4.0",
"dayjs": "^1.11.13",
"react": "^19.1.0",
"react-dom": "^19.1.0",
@@ -24,12 +25,12 @@
"tailwindcss": "^4.1.7"
},
"devDependencies": {
- "@vitest/coverage-v8": "^3.2.4",
"@eslint/js": "^9.25.0",
"@trivago/prettier-plugin-sort-imports": "^5.2.2",
"@types/react": "^19.1.2",
"@types/react-dom": "^19.1.2",
"@vitejs/plugin-react": "^4.4.1",
+ "@vitest/coverage-v8": "^3.2.4",
"eslint": "^9.25.0",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react-hooks": "^5.2.0",
diff --git a/frontend/src/entity/intervals/model/Interval.ts b/frontend/src/entity/intervals/model/Interval.ts
index 6efc49f6..9293b5bf 100644
--- a/frontend/src/entity/intervals/model/Interval.ts
+++ b/frontend/src/entity/intervals/model/Interval.ts
@@ -8,4 +8,6 @@ export interface Interval {
weekday?: number;
// only for MONTHLY
dayOfMonth?: number;
+ // only for CRON
+ cronExpression?: string;
}
diff --git a/frontend/src/entity/intervals/model/IntervalType.ts b/frontend/src/entity/intervals/model/IntervalType.ts
index d4292522..1137f82e 100644
--- a/frontend/src/entity/intervals/model/IntervalType.ts
+++ b/frontend/src/entity/intervals/model/IntervalType.ts
@@ -3,4 +3,5 @@ export enum IntervalType {
DAILY = 'DAILY',
WEEKLY = 'WEEKLY',
MONTHLY = 'MONTHLY',
+ CRON = 'CRON',
}
diff --git a/frontend/src/features/backups/ui/EditBackupConfigComponent.tsx b/frontend/src/features/backups/ui/EditBackupConfigComponent.tsx
index 737f45ac..64896808 100644
--- a/frontend/src/features/backups/ui/EditBackupConfigComponent.tsx
+++ b/frontend/src/features/backups/ui/EditBackupConfigComponent.tsx
@@ -2,6 +2,7 @@ import { InfoCircleOutlined } from '@ant-design/icons';
import {
Button,
Checkbox,
+ Input,
InputNumber,
Modal,
Select,
@@ -10,6 +11,7 @@ import {
TimePicker,
Tooltip,
} from 'antd';
+import { CronExpressionParser } from 'cron-parser';
import dayjs, { Dayjs } from 'dayjs';
import { useEffect, useMemo, useState } from 'react';
@@ -19,10 +21,11 @@ import type { Database } from '../../../entity/databases';
import { Period } from '../../../entity/databases/model/Period';
import { type Interval, IntervalType } from '../../../entity/intervals';
import { type Storage, getStorageLogoFromType, storageApi } from '../../../entity/storages';
+import { getUserTimeFormat } from '../../../shared/time';
import {
+ getUserTimeFormat as getIs12Hour,
getLocalDayOfMonth,
getLocalWeekday,
- getUserTimeFormat,
getUtcDayOfMonth,
getUtcWeekday,
} from '../../../shared/time/utils';
@@ -77,10 +80,12 @@ export const EditBackupConfigComponent = ({
const [isShowWarn, setIsShowWarn] = useState(false);
const timeFormat = useMemo(() => {
- const is12 = getUserTimeFormat();
+ const is12 = getIs12Hour();
return { use12Hours: is12, format: is12 ? 'h:mm A' : 'HH:mm' };
}, []);
+ const dateTimeFormat = useMemo(() => getUserTimeFormat(), []);
+
const updateBackupConfig = (patch: Partial<BackupConfig>) => {
setBackupConfig((prev) => (prev ? { ...prev, ...patch } : prev));
setIsUnsaved(true);
@@ -201,7 +206,8 @@ export const EditBackupConfigComponent = ({
Boolean(backupInterval?.interval) &&
(!backupInterval ||
((backupInterval.interval !== IntervalType.WEEKLY || displayedWeekday) &&
- (backupInterval.interval !== IntervalType.MONTHLY || displayedDayOfMonth))));
+ (backupInterval.interval !== IntervalType.MONTHLY || displayedDayOfMonth) &&
+ (backupInterval.interval !== IntervalType.CRON || backupInterval.cronExpression))));
return (
<div>
@@ -230,6 +236,7 @@ export const EditBackupConfigComponent = ({
{ label: 'Daily', value: IntervalType.DAILY },
{ label: 'Weekly', value: IntervalType.WEEKLY },
{ label: 'Monthly', value: IntervalType.MONTHLY },
+ { label: 'Cron', value: IntervalType.CRON },
]}
/>
</div>
@@ -269,33 +276,93 @@ export const EditBackupConfigComponent = ({
</div>
)}
- {backupInterval?.interval !== IntervalType.HOURLY && (
- <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">
- <div className="mb-1 min-w-[150px] sm:mb-0">Backup time of day</div>
- <TimePicker
- value={localTime}
- format={timeFormat.format}
- use12Hours={timeFormat.use12Hours}
- allowClear={false}
- size="small"
- className="w-full max-w-[200px] grow"
- onChange={(t) => {
- if (!t) return;
- const patch: Partial<Interval> = { timeOfDay: t.utc().format('HH:mm') };
-
- if (backupInterval?.interval === IntervalType.WEEKLY && displayedWeekday) {
- patch.weekday = getUtcWeekday(displayedWeekday, t);
- }
- if (backupInterval?.interval === IntervalType.MONTHLY && displayedDayOfMonth) {
- patch.dayOfMonth = getUtcDayOfMonth(displayedDayOfMonth, t);
+ {backupInterval?.interval === IntervalType.CRON && (
+ <>
+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">
+ <div className="mb-1 min-w-[150px] sm:mb-0">Cron expression (UTC)</div>
+ <div className="flex items-center">
+ <Input
+ value={backupInterval?.cronExpression || ''}
+ onChange={(e) => saveInterval({ cronExpression: e.target.value })}
+ placeholder="0 2 * * *"
+ size="small"
+ className="w-full max-w-[200px] grow"
+ />
+ <Tooltip
+ className="cursor-pointer"
+ title={
+ <div>
+ <div className="font-bold">
+ Cron format: minute hour day month weekday (UTC)
+ </div>
+ <div className="mt-1">Examples:</div>
+ <div>β€’ 0 2 * * * - Daily at 2:00 AM UTC</div>
+ <div>β€’ 0 */6 * * * - Every 6 hours</div>
+ <div>β€’ 0 3 * * 1 - Every Monday at 3:00 AM UTC</div>
+ <div>β€’ 30 4 1,15 * * - 1st and 15th at 4:30 AM UTC</div>
+ </div>
+ }
+ >
+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />
+ </Tooltip>
+ </div>
+ </div>
+ {backupInterval?.cronExpression &&
+ (() => {
+ try {
+ const interval = CronExpressionParser.parse(backupInterval.cronExpression, {
+ tz: 'UTC',
+ });
+ const nextRun = interval.next().toDate();
+ return (
+ <div className="mb-1 flex w-full flex-col items-start text-xs text-gray-600 sm:flex-row sm:items-center dark:text-gray-400">
+ <div className="mb-1 min-w-[150px] sm:mb-0" />
+ <div className="text-gray-600 dark:text-gray-400">
+ Next run {dayjs(nextRun).local().format(dateTimeFormat.format)}
+ <br />({dayjs(nextRun).fromNow()})
+ </div>
+ </div>
+ );
+ } catch {
+ return (
+ <div className="mb-1 flex w-full flex-col items-start text-red-500 sm:flex-row sm:items-center">
+ <div className="mb-1 min-w-[150px] sm:mb-0" />
+ <div className="text-red-500">Invalid cron expression</div>
+ </div>
+ );
}
-
- saveInterval(patch);
- }}
- />
- </div>
+ })()}
+ </>
)}
+ {backupInterval?.interval !== IntervalType.HOURLY &&
+ backupInterval?.interval !== IntervalType.CRON && (
+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">
+ <div className="mb-1 min-w-[150px] sm:mb-0">Backup time of day</div>
+ <TimePicker
+ value={localTime}
+ format={timeFormat.format}
+ use12Hours={timeFormat.use12Hours}
+ allowClear={false}
+ size="small"
+ className="w-full max-w-[200px] grow"
+ onChange={(t) => {
+ if (!t) return;
+ const patch: Partial<Interval> = { timeOfDay: t.utc().format('HH:mm') };
+
+ if (backupInterval?.interval === IntervalType.WEEKLY && displayedWeekday) {
+ patch.weekday = getUtcWeekday(displayedWeekday, t);
+ }
+ if (backupInterval?.interval === IntervalType.MONTHLY && displayedDayOfMonth) {
+ patch.dayOfMonth = getUtcDayOfMonth(displayedDayOfMonth, t);
+ }
+
+ saveInterval(patch);
+ }}
+ />
+ </div>
+ )}
+
<div className="mt-4 mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">
<div className="mb-1 min-w-[150px] sm:mb-0">Retry backup if failed</div>
<div className="flex items-center">
diff --git a/frontend/src/features/backups/ui/ShowBackupConfigComponent.tsx b/frontend/src/features/backups/ui/ShowBackupConfigComponent.tsx
index cae59e33..0a7d71bb 100644
--- a/frontend/src/features/backups/ui/ShowBackupConfigComponent.tsx
+++ b/frontend/src/features/backups/ui/ShowBackupConfigComponent.tsx
@@ -1,5 +1,6 @@
import { InfoCircleOutlined } from '@ant-design/icons';
import { Tooltip } from 'antd';
+import { CronExpressionParser } from 'cron-parser';
import dayjs from 'dayjs';
import { useMemo } from 'react';
import { useEffect, useState } from 'react';
@@ -10,7 +11,12 @@ import type { Database } from '../../../entity/databases';
import { Period } from '../../../entity/databases/model/Period';
import { IntervalType } from '../../../entity/intervals';
import { getStorageLogoFromType } from '../../../entity/storages/models/getStorageLogoFromType';
-import { getLocalDayOfMonth, getLocalWeekday, getUserTimeFormat } from '../../../shared/time/utils';
+import { getUserTimeFormat } from '../../../shared/time';
+import {
+ getUserTimeFormat as getIs12Hour,
+ getLocalDayOfMonth,
+ getLocalWeekday,
+} from '../../../shared/time/utils';
interface Props {
database: Database;
@@ -31,6 +37,7 @@ const intervalLabels = {
[IntervalType.DAILY]: 'Daily',
[IntervalType.WEEKLY]: 'Weekly',
[IntervalType.MONTHLY]: 'Monthly',
+ [IntervalType.CRON]: 'Cron',
};
const periodLabels = {
@@ -57,13 +64,15 @@ export const ShowBackupConfigComponent = ({ database }: Props) => {
// Detect user's preferred time format (12-hour vs 24-hour)
const timeFormat = useMemo(() => {
- const is12Hour = getUserTimeFormat();
+ const is12Hour = getIs12Hour();
return {
use12Hours: is12Hour,
format: is12Hour ? 'h:mm A' : 'HH:mm',
};
}, []);
+ const dateTimeFormat = useMemo(() => getUserTimeFormat(), []);
+
useEffect(() => {
if (database.id) {
backupConfigApi.getBackupConfigByDbID(database.id).then((res) => {
@@ -131,13 +140,45 @@ export const ShowBackupConfigComponent = ({ database }: Props) => {
</div>
)}
- {backupInterval?.interval !== IntervalType.HOURLY && (
- <div className="mb-1 flex w-full items-center">
- <div className="min-w-[150px]">Backup time of day</div>
- <div>{formattedTime}</div>
- </div>
+ {backupInterval?.interval === IntervalType.CRON && (
+ <>
+ <div className="mb-1 flex w-full items-center">
+ <div className="min-w-[150px]">Cron expression (UTC)</div>
+ <code className="rounded bg-gray-100 px-2 py-0.5 text-sm dark:bg-gray-700">
+ {backupInterval?.cronExpression || ''}
+ </code>
+ </div>
+ {backupInterval?.cronExpression &&
+ (() => {
+ try {
+ const interval = CronExpressionParser.parse(backupInterval.cronExpression, {
+ tz: 'UTC',
+ });
+ const nextRun = interval.next().toDate();
+ return (
+ <div className="mb-1 flex w-full items-center text-xs text-gray-600 dark:text-gray-400">
+ <div className="min-w-[150px]" />
+ <div>
+ Next run {dayjs(nextRun).local().format(dateTimeFormat.format)}
+ <br />({dayjs(nextRun).fromNow()})
+ </div>
+ </div>
+ );
+ } catch {
+ return null;
+ }
+ })()}
+ </>
)}
+ {backupInterval?.interval !== IntervalType.HOURLY &&
+ backupInterval?.interval !== IntervalType.CRON && (
+ <div className="mb-1 flex w-full items-center">
+ <div className="min-w-[150px]">Backup time of day</div>
+ <div>{formattedTime}</div>
+ </div>
+ )}
+
<div className="mb-1 flex w-full items-center">
<div className="min-w-[150px]">Retry if failed</div>
<div>{backupConfig.isRetryIfFailed ? 'Yes' : 'No'}</div>
diff --git a/frontend/src/shared/time/getUserTimeFormat.ts b/frontend/src/shared/time/getUserTimeFormat.ts
index 01ce3a7d..d3abef35 100644
--- a/frontend/src/shared/time/getUserTimeFormat.ts
+++ b/frontend/src/shared/time/getUserTimeFormat.ts
@@ -1,23 +1,67 @@
-export const getUserTimeFormat = () => {
+// Detect date order (MDY, DMY, YMD) and separator from user's locale
+const getLocaleDateFormat = () => {
+ const locale = navigator.language || 'en-US';
+
+ // Use a test date where day, month, year are all different: March 15, 2023
+ const testDate = new Date(2023, 2, 15);
+ const formatted = testDate.toLocaleDateString(locale);
+
+ // Detect separator: . / or -
+ let separator = '/';
+ if (formatted.includes('.')) separator = '.';
+ else if (formatted.includes('-')) separator = '-';
+
+ // Detect order by checking position of 15 (day), 3 (month), 2023/23 (year)
+ const parts = formatted.split(/[./-]/);
+ const dayIndex = parts.findIndex((p) => p === '15');
+ const monthIndex = parts.findIndex((p) => p === '3' || p === '03');
+ const yearIndex = parts.findIndex((p) => p === '2023' || p === '23');
+
+ // Default to DMY if detection fails
+ let dateFormat = `DD${separator}MM${separator}YYYY`;
+ let shortDateFormat = `DD MMM YYYY`;
+
+ if (yearIndex === 0) {
+ // YMD (China, Japan, Korea, ISO)
+ dateFormat = `YYYY${separator}MM${separator}DD`;
+ shortDateFormat = `YYYY MMM DD`;
+ } else if (monthIndex === 0 && dayIndex === 1) {
+ // MDY (USA)
+ dateFormat = `MM${separator}DD${separator}YYYY`;
+ shortDateFormat = `MMM DD, YYYY`;
+ } else {
+ // DMY (Europe, Russia, most of the world)
+ dateFormat = `DD${separator}MM${separator}YYYY`;
+ shortDateFormat = `DD MMM YYYY`;
+ }
+
+ return { dateFormat, shortDateFormat, separator };
+};
+
+// Detect if user prefers 12-hour time format
+const getIs12HourFormat = () => {
const locale = navigator.language || 'en-US';
const testDate = new Date(2023, 0, 1, 13, 0, 0); // 1 PM
const timeString = testDate.toLocaleTimeString(locale, { hour: 'numeric' });
- const is12Hour = timeString.includes('PM') || timeString.includes('AM');
+ return timeString.includes('PM') || timeString.includes('AM');
+};
+
+export const getUserTimeFormat = () => {
+ const { dateFormat } = getLocaleDateFormat();
+ const is12Hour = getIs12HourFormat();
return {
use12Hours: is12Hour,
- format: is12Hour ? 'DD.MM.YYYY h:mm:ss A' : 'DD.MM.YYYY HH:mm:ss',
+ format: is12Hour ? `${dateFormat} h:mm A` : `${dateFormat} HH:mm`,
};
};
export const getUserShortTimeFormat = () => {
- const locale = navigator.language || 'en-US';
- const testDate = new Date(2023, 0, 1, 13, 0, 0); // 1 PM
- const timeString = testDate.toLocaleTimeString(locale, { hour: 'numeric' });
- const is12Hour = timeString.includes('PM') || timeString.includes('AM');
+ const { shortDateFormat } = getLocaleDateFormat();
+ const is12Hour = getIs12HourFormat();
return {
use12Hours: is12Hour,
- format: is12Hour ? 'DD MMM YYYY h:mm A' : 'DD MMM YYYY HH:mm',
+ format: is12Hour ? `${shortDateFormat} h:mm A` : `${shortDateFormat} HH:mm`,
};
};