autorestic/src/cron.ts

32 lines
1.1 KiB
TypeScript
Raw Normal View History

2020-05-17 11:13:02 +02:00
import CronParser from 'cron-parser'
2020-11-06 23:51:23 +01:00
import { config } from './'
2020-05-17 11:13:02 +02:00
import { checkAndConfigureBackendsForLocations } from './backend'
2020-05-17 18:13:50 +02:00
import { Location } from './types'
2020-05-17 11:13:02 +02:00
import { backupLocation } from './backup'
2020-05-17 18:13:50 +02:00
import { readLock, writeLock } from './lock'
2020-05-17 11:13:02 +02:00
const runCronForLocation = (name: string, location: Location) => {
2020-05-17 18:13:50 +02:00
const lock = readLock()
2020-05-17 11:13:02 +02:00
const parsed = CronParser.parseExpression(location.cron || '')
const last = parsed.prev()
2020-05-17 18:13:50 +02:00
if (!lock.crons[name] || last.toDate().getTime() > lock.crons[name].lastRun) {
2020-05-17 11:13:02 +02:00
backupLocation(name, location)
2020-05-17 18:13:50 +02:00
lock.crons[name] = { lastRun: Date.now() }
writeLock(lock)
2020-05-17 11:13:02 +02:00
} else {
console.log(`${name.yellow} ▶ Skipping. Scheduled for: ${parsed.next().toString().underline.blue}`)
2020-05-17 11:13:02 +02:00
}
}
export const runCron = () => {
const locationsWithCron = Object.entries(config.locations).filter(([name, { cron }]) => !!cron)
checkAndConfigureBackendsForLocations(Object.fromEntries(locationsWithCron))
console.log('\nRunning cron jobs'.underline.gray)
2020-11-06 23:51:23 +01:00
for (const [name, location] of locationsWithCron) runCronForLocation(name, location)
2020-05-17 11:13:02 +02:00
console.log('\nFinished!'.underline + ' 🎉')
}