修复定时删除日志

This commit is contained in:
whyour
2022-02-19 17:36:49 +08:00
parent cf5f1b6f25
commit 7d6e1d3e3d
9 changed files with 146 additions and 96 deletions
+1 -1
View File
@@ -4,7 +4,7 @@ import { DataTypes, Model, ModelDefined } from 'sequelize';
export class Crontab {
name?: string;
command: string;
schedule: string;
schedule?: string;
timestamp?: string;
saved?: boolean;
id?: number;
+18
View File
@@ -7,11 +7,15 @@ import EnvService from '../services/env';
import _ from 'lodash';
import { DependenceModel } from '../data/dependence';
import { Op } from 'sequelize';
import SystemService from '../services/system';
import ScheduleService from '../services/schedule';
export default async () => {
const cronService = Container.get(CronService);
const envService = Container.get(EnvService);
const dependenceService = Container.get(DependenceService);
const systemService = Container.get(SystemService);
const scheduleService = Container.get(ScheduleService);
// 初始化更新所有任务状态为空闲
await CrontabModel.update(
@@ -53,6 +57,20 @@ export default async () => {
// 初始化保存一次ck和定时任务数据
await cronService.autosave_crontab();
await envService.set_envs();
// 运行删除日志任务
const data = await systemService.getLogRemoveFrequency();
if (data && data.info && data.info.frequency) {
const cron = {
id: data.id,
name: '删除日志',
command: `ql rmlog ${data.info.frequency}`,
};
await scheduleService.createIntervalTask(cron, {
days: data.info.frequency,
runImmediately: true,
});
}
};
function randomSchedule(from: number, to: number) {
+75 -7
View File
@@ -3,24 +3,33 @@ import winston from 'winston';
import nodeSchedule from 'node-schedule';
import { Crontab } from '../data/cron';
import { exec } from 'child_process';
import {
ToadScheduler,
SimpleIntervalJob,
Task,
SimpleIntervalSchedule,
} from 'toad-scheduler';
@Service()
export default class ScheduleService {
private scheduleStacks = new Map<number, nodeSchedule.Job>();
private scheduleStacks = new Map<string, nodeSchedule.Job>();
private intervalSchedule = new ToadScheduler();
constructor(@Inject('logger') private logger: winston.Logger) {}
async generateSchedule({ id = 0, command, name, schedule }: Crontab) {
async createCronTask({ id = 0, command, name, schedule = '' }: Crontab) {
const _id = this.formatId(id);
this.logger.info(
'[创建定时任务],任务ID: %scron: %s,任务名: %s,执行命令: %s',
id,
'[创建cron任务],任务ID: %scron: %s,任务名: %s,执行命令: %s',
_id,
schedule,
name,
command,
);
this.scheduleStacks.set(
id,
_id,
nodeSchedule.scheduleJob(id + '', schedule, async () => {
try {
exec(command, async (error, stdout, stderr) => {
@@ -55,8 +64,67 @@ export default class ScheduleService {
);
}
async cancelSchedule({ id = 0, name }: Crontab) {
async cancelCronTask({ id = 0, name }: Crontab) {
const _id = this.formatId(id);
this.logger.info('[取消定时任务],任务名:%s', name);
this.scheduleStacks.has(id) && this.scheduleStacks.get(id)?.cancel();
this.scheduleStacks.has(_id) && this.scheduleStacks.get(_id)?.cancel();
}
async createIntervalTask(
{ id = 0, command, name = '' }: Crontab,
schedule: SimpleIntervalSchedule,
) {
const _id = this.formatId(id);
this.logger.info(
'[创建interval任务],任务ID: %s,任务名: %s,执行命令: %s',
_id,
name,
command,
);
const task = new Task(name, async () => {
try {
exec(command, async (error, stdout, stderr) => {
if (error) {
await this.logger.info(
'执行任务%s失败,时间:%s, 错误信息:%j',
command,
new Date().toLocaleString(),
error,
);
}
if (stderr) {
await this.logger.info(
'执行任务%s失败,时间:%s, 错误信息:%j',
command,
new Date().toLocaleString(),
stderr,
);
}
});
} catch (error) {
await this.logger.info(
'执行任务%s失败,时间:%s, 错误信息:%j',
command,
new Date().toLocaleString(),
error,
);
} finally {
}
});
const job = new SimpleIntervalJob({ ...schedule }, task, _id);
this.intervalSchedule.addIntervalJob(job);
}
async cancelIntervalTask({ id = 0, name }: Crontab) {
const _id = this.formatId(id);
this.logger.info('[取消interval任务],任务ID: %s,任务名:%s', _id, name);
this.intervalSchedule.removeById(_id);
}
private formatId(id: number): string {
return String(id);
}
}
+6 -4
View File
@@ -24,7 +24,7 @@ export default class SystemService {
public async getLogRemoveFrequency() {
const doc = await this.getDb({ type: AuthDataType.removeLogFrequency });
return (doc && doc.info) || {};
return doc || {};
}
private async updateAuthDb(payload: AuthInfo): Promise<any> {
@@ -65,11 +65,13 @@ export default class SystemService {
id: result.id,
name: '删除日志',
command: `ql rmlog ${frequency}`,
schedule: `5 23 */${frequency} * *`,
};
await this.scheduleService.cancelSchedule(cron);
await this.scheduleService.cancelIntervalTask(cron);
if (frequency > 0) {
await this.scheduleService.generateSchedule(cron);
await this.scheduleService.createIntervalTask(cron, {
days: frequency,
runImmediately: true,
});
}
return { code: 200, data: { ...cron } };
}
+2 -2
View File
@@ -360,9 +360,9 @@ export default class UserService {
command: `ql rmlog ${frequency}`,
schedule: `5 23 */${frequency} * *`,
};
await this.scheduleService.cancelSchedule(cron);
await this.scheduleService.cancelCronTask(cron);
if (frequency > 0) {
await this.scheduleService.generateSchedule(cron);
await this.scheduleService.createCronTask(cron);
}
return { code: 200, data: { ...cron } };
}