'use strict'; /** * 为何要把分属于不同业务模块的job集中到此处? * 如果后续要把任务执行与web服务器分离,就会很方便,就算不分离,也没多大坏处。 * 任务包括: * transaction : { * 1. 每小时去清理指定startTime的地产,将 * { * status: -> 1, * price: -> price * (1 + profit), * currentOwner: -> '' * } * 2. 将currentOwner对应的用户的asset.log加上a * } */ const mongoose = require('mongoose'); const Fund = require('../modules/fund/fund.model'); const exec = require('child_process').exec; async function confirm (job = mock, done = mock) { mylog.info('[Schedule Job] 矿晶确认程序开始执行......'); const unconfirmed = await Fund.find({ 'fundList.status': 0 }); mylog.info('共有' + unconfirmed.length + '用户需要确认'); unconfirmed.forEach(async (fund) => { const len = fund.fundList.length || 0; let acc = 0; for (let i = 0; i < len; ++i) { const fundItem = fund.fundList[i]; if (fundItem && fundItem.status === 0) { ++acc; await Fund.findByIdAndUpdate(fund.id, { $set: { [`fundList.${i}.status`]: 1 // 确认激活 } }); } } mylog.info(`用户${fund.userId} 共更新${acc}条`); job.touch(); }); return typeof done === 'function' && done('矿晶确认完成'); } async function mineJob (job = mock, done = mock) { const rl = exec('node ./src/jobs/mine.js'); rl.stderr.on('data', function (data) { mylog.error('[mine]定时任务出错\n'); mylog.error(data); }); rl.on('close', function (code) { mylog.info('child process exited with code ' + code); // 输出到控制台 mylog.info('挖矿程序执行完毕'); }); rl.on('message', function () { job.touch(); }); rl.on('exit', function () { typeof done === 'function' && done('挖矿程序执行完毕'); }); } const jobs = [ // { // name: 'mine', // processor: mineJob, // type: 'every', // slot: '0 0 3 * * *', // priority: 'highest', // unique: { // id: 'mine' // }, // skipImmediate: true, // timezone: "ETC/GMT+8" // }, { name: 'mineCorn', processor: mineJob, type: 'every', slot: '0 0 2 * * *', priority: 'highest', unique: { id: 'mine' }, skipImmediate: true, timezone: "ETC/GMT+8" }, { name: 'confirm', processor: confirm, type: 'every', slot: '0 0/10 * * * *', // 59 */1 * * * priority: 'highest', unique: { id: 'confirm' }, // skipImmediate: true, timezone: "ETC/GMT+8" } ]; function mountJobs (Job) { jobs.map(jobConfig => { const { name, processor, type, slot, priority, unique, skipImmediate, timezone } = jobConfig; Job.define(name, { timezone, skipImmediate, priority, unique: { 'data.type': 'active', 'data.userId': unique.id } }, processor); Job[type](slot, name); }); } module.exports = Job => mountJobs(Job);