Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Translated the file src/user/jobs.js from JS to TS #104

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions src/user/jobs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import * as winston from 'winston';
import * as cronJob from 'cron';
import * as db from '../database';
import * as meta from '../meta';

const jobs = {};

module.exports = function (User) {
User.startJobs = function () {
winston.verbose('[user/jobs] (Re-)starting jobs...');

let { digestHour } = meta.config;

// Fix digest hour if invalid
if (isNaN(digestHour)) {
digestHour = 17;
} else if (digestHour > 23 || digestHour < 0) {
digestHour = 0;
}

User.stopJobs();

startDigestJob('digest.daily', `0 ${digestHour} * * *`, 'day');
startDigestJob('digest.weekly', `0 ${digestHour} * * 0`, 'week');
startDigestJob('digest.monthly', `0 ${digestHour} 1 * *`, 'month');

jobs['reset.clean'] = new cronJob('0 0 * * *', User.reset.clean, null, true);
winston.verbose('[user/jobs] Starting job (reset.clean)');

winston.verbose(`[user/jobs] jobs started`);
};

function startDigestJob(name, cronString, term) {
jobs[name] = new cronJob(cronString, (async () => {
winston.verbose(`[user/jobs] Digest job (${name}) started.`);
try {
if (name === 'digest.weekly') {
const counter = await db.increment('biweeklydigestcounter');
if (counter % 2) {
await User.digest.execute({ interval: 'biweek' });
}
}
await User.digest.execute({ interval: term });
} catch (err) {
winston.error(err.stack);
}
}), null, true);
winston.verbose(`[user/jobs] Starting job (${name})`);
}

User.stopJobs = function () {
let terminated = 0;
// Terminate any active cron jobs
for (const jobId of Object.keys(jobs)) {
winston.verbose(`[user/jobs] Terminating job (${jobId})`);
jobs[jobId].stop();
delete jobs[jobId];
terminated += 1;
}
if (terminated > 0) {
winston.verbose(`[user/jobs] ${terminated} jobs terminated`);
}
};
};