forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackup-scheduler.ts
More file actions
50 lines (42 loc) · 1.46 KB
/
backup-scheduler.ts
File metadata and controls
50 lines (42 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
* Copyright (c) 2023 Hengyang Zhang
*
* This software is released under the MIT License.
* https://opensource.org/licenses/MIT
*/
import processor from "@service/backup/processor"
import optionHolder from "@service/components/option-holder"
import { MILL_PER_MINUTE } from "@util/time"
import alarmManager from "./alarm-manager"
const ALARM_NAME = 'auto-backup-data'
class BackupScheduler {
needBackup = false
/**
* Interval of milliseconds
*/
interval: number = 0
init() {
optionHolder.get().then(opt => this.handleOption(opt))
optionHolder.addChangeListener(opt => this.handleOption(opt))
}
private handleOption(option: timer.option.BackupOption) {
const { autoBackUp, backupType, autoBackUpInterval = 0 } = option || {}
this.needBackup = backupType !== "none" && !!backupType && !!autoBackUp
this.interval = autoBackUpInterval * MILL_PER_MINUTE
if (this.needSchedule()) {
alarmManager.setInterval(ALARM_NAME, this.interval, () => this.doBackup())
} else {
alarmManager.remove(ALARM_NAME)
}
}
private needSchedule(): boolean {
return !!this.needBackup && !!this.interval
}
private async doBackup(): Promise<void> {
const result = await processor.syncData()
if (!result.success) {
console.warn(`Failed to backup ts=${Date.now()}, msg=${result.errorMsg}`)
}
}
}
export default BackupScheduler