// app/schedule/system_log_cleanup.js 'use strict'; /** @type {number} 默认单批硬删除行数 */ const DEFAULT_BATCH_SIZE = 2000; /** @type {number} 默认批间休眠最小毫秒数 */ const DEFAULT_SLEEP_MIN_MS = 100; /** @type {number} 默认批间休眠最大毫秒数 */ const DEFAULT_SLEEP_MAX_MS = 500; /** * 系统日志超期清理定时任务。 * * 默认每日凌晨 03:00:00(cron:秒 分 时 日 月 周)在单 worker 中执行一次, * 硬删除 wms_system_log 超过保留天数(默认 60 天)的日志以释放磁盘空间,避开 08:00–23:00 业务高峰。 * cron 从 config.systemLogCleanup.cron 读取(config.default.js 提供默认值), * 本地环境可在 config.local.js 覆盖为短间隔以便快速验证,不影响生产 03:00 触发时间。 * 保留天数由 service.systems.systemLog 读取 config.systemLogCleanup.retainDays(默认 60,非法值回退 60); * 由 config.systemLogCleanup 控制:enable=false 时不注册本任务; * 实际清理逻辑收敛在 service.systems.systemLog.cleanupExpiredSystemLogs。 * * @param {Object} app Egg 应用实例。 * @return {Object} 定时任务定义(含 schedule 与 task)。 */ module.exports = app => { const cleanupConfig = (app.config && app.config.systemLogCleanup) || {}; // cron 从配置读取,缺省时回退为每日凌晨 03:00(cron 格式:秒 分 时 日 月 周) const cleanupCron = typeof cleanupConfig.cron === 'string' && cleanupConfig.cron ? cleanupConfig.cron : '0 0 3 * * *'; return { schedule: { cron: cleanupCron, type: 'worker', immediate: false, disable: cleanupConfig.enable === false, }, /** * 执行系统日志超期清理。 * * 采用单 worker 防重入:上一轮未结束时跳过本轮; * 任务失败只记录错误日志,不向上抛出,避免导致 schedule 崩溃。 * * @param {Object} ctx Egg 上下文。 * @return {Promise} 无返回值。 */ async task(ctx) { const scheduleName = 'system_log_cleanup'; if (ctx.app._systemLogCleanupRunning) { ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`); return; } ctx.app._systemLogCleanupRunning = true; const startedAt = Date.now(); try { const config = ctx.app.config.systemLogCleanup || {}; // 保留天数(retainDays)由 service 读取 config.systemLogCleanup.retainDays 自行解析,此处不再透传 const options = { batchSize: Number(config.batchSize) > 0 ? Math.floor(Number(config.batchSize)) : DEFAULT_BATCH_SIZE, sleepMinMs: Number(config.sleepMinMs) >= 0 ? Math.floor(Number(config.sleepMinMs)) : DEFAULT_SLEEP_MIN_MS, sleepMaxMs: Number(config.sleepMaxMs) >= 0 ? Math.floor(Number(config.sleepMaxMs)) : DEFAULT_SLEEP_MAX_MS, }; const summary = await ctx.service.systems.systemLog.cleanupExpiredSystemLogs(options); ctx.logger.info( `[${scheduleName}] 本轮完成 skipped=${summary.skipped} boundary_id=${summary.boundary_id}` + ` batches=${summary.batch_count} deleted=${summary.deleted_rows}` + ` duration=${Date.now() - startedAt}ms` ); } catch (error) { ctx.logger.error(`[${scheduleName}] 执行失败: ${error.message}`); } finally { ctx.app._systemLogCleanupRunning = false; } }, }; };