1
0
Files
jecnarozvrh/cron-runner.js
2025-12-20 20:52:08 +01:00

57 lines
1.8 KiB
JavaScript

/*
* Copyright (C) 2025 Jakub Žitník
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
import cron from 'node-cron';
import { exec } from 'child_process';
import { scheduleRules, toMinutes } from './scheduleRules.js';
function runScraper() {
console.log(`Running scraper at ${new Date().toLocaleString()}...`);
exec('node scrape/scraper.js', (error, stdout, stderr) => {
if (error) {
console.error(`Scraper error: ${error.message}`);
return;
}
if (stderr) console.error(`Scraper stderr: ${stderr}`);
if (stdout) console.log(`Scraper output:\n${stdout}`);
});
}
function createSchedules(rules) {
rules.forEach(rule => {
const startMin = toMinutes(rule.start);
const endMin = toMinutes(rule.end === "0:00" ? "24:00" : rule.end);
const times = [];
const adjustedEnd = endMin <= startMin ? endMin + 1440 : endMin;
for (let t = startMin; t < adjustedEnd; t += rule.interval) {
const h = Math.floor(t % 1440 / 60);
const m = t % 60;
times.push({ h, m });
}
times.forEach(({ h, m }) => {
const cronExpr = `${m} ${h} * * *`;
cron.schedule(cronExpr, runScraper);
console.log(`Scheduled: ${cronExpr}`);
});
});
}
// Run immediately at start
runScraper();
createSchedules(scheduleRules);
console.log('Cron scheduler started with custom intervals.');