clear-task.js 1.4 KB
const dayjs = require('dayjs');
const {logger} = require('../../libs/logger');
const {sendMessage} = require('../../libs/influx-report');
const {mysqlPool} = require('../../libs/mysql');

module.exports = async() => {
  const deleteTables = [{
    table: 'price_trend_day',
    beforeTime: dayjs().subtract(3, 'day').unix()
  }, {
    table: 'price_trend_month',
    beforeTime: dayjs().subtract(30, 'day').unix()
  }, {
    table: 'price_trend_sixty_day',
    beforeTime: dayjs().subtract(60, 'day').unix()
  }, {
    table: 'price_trend_half_year',
    beforeTime: dayjs().subtract(180, 'day').unix()
  }];

  try {
    const results = await Promise.all(deleteTables.map(dt => {
      return mysqlPool.delete(`DELETE FROM \`${dt.table}\` WHERE \`create_time\` < :beforeTime`, {
        beforeTime: dt.beforeTime
      });
    }));

    results.forEach((result, inx) => {
      if (result <= 0) {
        logger.error(`[price-line-clear-task]删除数据失败, ${deleteTables[inx].table}, endTime: ${deleteTables[inx].beforeTime}`);
      } else {
        logger.info(`[price-line-clear-task]清理成功, ${deleteTables[inx].table}, endTime: ${deleteTables[inx].beforeTime}, records: ${result}`);
      }
      sendMessage(result, new Date().getTime() * 1000000, `clear-task-${deleteTables[inx].table}`);
    });
  } catch (error) {
    logger.error(`[price-line-clear-task]删除数据错误, error: ${error.stack}`);
  }
};