在 Egg.js 中,可以通过以下两种方式向 app.runSchedule('updateCodeState') 传递参数:

  1. 通过启动参数传递

在启动 Egg.js 时,可以通过命令行参数传递参数,例如:

$ egg-bin dev --foo=bar

在定时任务中可以通过 app.config 获取启动参数,例如:

// app/schedule/update_code_state.js
const Subscription = require('egg').Subscription;

class UpdateCodeState extends Subscription {
  static get schedule() {
    return {
      interval: '1h',
      type: 'worker',
    };
  }

  async subscribe() {
    const { foo } = this.ctx.app.config;
    console.log('foo:', foo);
    // ...
  }
}

module.exports = UpdateCodeState;
  1. 通过参数对象传递

可以通过构造一个包含参数的对象,并将其作为 runSchedule 方法的第二个参数传递,例如:

// app/controller/home.js
class HomeController extends Controller {
  async index() {
    const { ctx, app } = this;
    await app.runSchedule('updateCodeState', { foo: 'bar' });
    ctx.body = 'Hello World';
  }
}

module.exports = HomeController;

在定时任务中可以通过 this.args 获取传递的参数,例如:

// app/schedule/update_code_state.js
const Subscription = require('egg').Subscription;

class UpdateCodeState extends Subscription {
  static get schedule() {
    return {
      interval: '1h',
      type: 'worker',
    };
  }

  async subscribe() {
    const { foo } = this.args[0];
    console.log('foo:', foo);
    // ...
  }
}

module.exports = UpdateCodeState;

注意,当使用第二种方式传递参数时,runSchedule 方法的第一个参数必须与定时任务的文件名相同。例如,对于 app/schedule/update_code_state.js 文件,传递的第一个参数必须是 'updateCodeState'

Egg.js 定时任务参数传递:启动参数和对象传递

原文地址: https://www.cveoy.top/t/topic/npoZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录