1

我在安排时使用节点议程我能够成功保存作业并且它运行良好。但是在重新启动服务器时,以前的作业没有重新开始。不知道为什么,我尝试了一些在网上找到的解决方案,但无法使其工作。谁能帮我这个。

  • 我正在将 Nodemon 与 node express 一起使用。
  • 我正在使用 API 调用创建计划

下面是app.js文件

'use strict';

require('dotenv').config();

const express = require('express');

const { initialize_mongodb_database_connection } = require('./helpers/mongodb_database');
const bodyParser = require('body-parser');

const Agenda = require('agenda');
const app = express();

let logger    = require('logger');
let chalk     = require('chalk');
let moment    = require('moment');
let mongoose  = require('mongoose');

const agenda = new Agenda({
    db: {address: process.env.MONGODB_URI, collection: 'scheduled_reports'},
    processEvery: '30 seconds'
});

app.use(bodyParser.json());

//
//  Parse application/x-www-form-urlencoded
//
app.use(bodyParser.urlencoded({extended: false}));

app.use(require('./routes/v1/schedule_report/schedule_report_routes'));

initialize_mongodb_database_connection();

sequr_app(app, [dummy_routes], {
    staticDir: true,
});

let gracefulExit = function() {
    if (mongoose.connection.readyState === 0) {
        return process.exit(0);
    }
    mongoose.connection.close(function() {
        return agenda.stop(function() {
            logger.info({});
            logger.info(chalk.bold("---------------------[ Server stopped at %s Uptime: %s ]---------------------------"), moment().format("YYYY-MM-DD HH:mm:ss.SSS"), moment.duration(process.uptime() * 1000).humanize());
            return process.exit(0);
        });
    });
};

process.on("SIGINT", gracefulExit).on("SIGTERM", gracefulExit);

这是我的议程文件,我在其中路由 API 调用以创建时间表

const Agenda = require('agenda');
var nodemailer = require('nodemailer');

var transporter = nodemailer.createTransport({
    service: 'gmail',
    host: 'smtp.gmail.com',
    auth: {
      user: 'xx-xx@gmail.com',
      pass: 'xx-xx-xx'
    }
  });

  var mailOptions = {
    from: 'example@example.com',
    to: 'Example@gmail.com',
    subject: 'Sending Email using Node.js',
    text: 'Agenda Test'
  };

  
const agenda = new Agenda({
    db: {address: process.env.MONGODB_URI, collection: 'agendaJobs'},
    processEvery: '30 seconds'
});

agenda.start();
agenda.defaultConcurrency(5);

const scheduleReport = async(report_data) => {

    // HERE SCHEDULING/CREATING AGENDA SCHEDULE

    agenda.on('start', job => {
        console.log('-------------------------------------STARTED-----------------------------------------------');
        console.log('Job %s starting', job.attrs.name);
        console.log('-------------------------------------------------------------------------------------------');
    });

    const {
        report_name,
        priority
    } = report_data;

    agenda.define(report_name, {priority: priority, concurrency: 10}, (job, done) => {
        const dateNow = new Date();
        const data = job.attrs.data;

        // The job.attrs.data is stored in our MongoDB collection so that it can be used to run the jobs.

        transporter.sendMail(mailOptions, function(error, info){
            if (error) {
              console.log(error);
            } else {
        //const date = new Date.now();
              console.log('Email sent: ' + info.response + dateNow);
              console.log(`Job ${job.attrs.name} finished`);
    
            }
          },done());
      });

      // HERE CREATING SCHEUDLE
      await createWeeklySchedule(report_data);

      agenda.on('complete', job => {
        console.log('---------------------------------------FINISHED---------------------------------------------');
        console.log(`Job ${job.attrs.name} completed succesfully...`);
        console.log('--------------------------------------------------------------------------------------------');
    });
    
}

const createWeeklySchedule = async(data) => {
    const {
        report_name,
        schedule_info,
        scheduled_timezone,
        time_cron
    } = data;
    const weeklyReport = agenda.create(report_name, {data: schedule_info});
    await agenda.start();
    await agenda.every(time_cron,report_name);
    console.log('Job successfully saved');
}

module.exports = scheduleReport;

另外我正在使用 app.js 启动应用程序main

4

0 回答 0