首页 > 解决方案 > 将带参数的函数传递给 cronjob

问题描述

我们在 typescript 项目中使用cron包。我看到的使用模式如下:

function jobUpdateVerStat() { // defined };
jobExecuteHourly = new CronJob('0 1 * * * *', jobUpdateVerStat);

我需要将参数传递sessjobUpdateVerStat. 因为这不起作用

const sess = getSess();
jobExecuteHourly = new CronJob('0 1 * * * *', jobUpdateVerStat(sess));

我查看了Cronjob看起来像这样的构造函数

constructor(cronTime: string | Date | Moment, onTick: CronCommand (..some more parameter..))

CronCommand的声明类型是这样的

export declare type CronCommand = (() => void) | string | { command: string, args?: ReadonlyArray<string>, options?: SpawnOptions};

因此,我根据此信息尝试了以下操作,但似乎都不起作用...这是否仅意味着该程序包不支持带参数的函数的预定运行?通常不希望将参数传递给 cronjob 还是我错过了一个明显的提示来完成这项工作?

  // function updateVersionStatus(sess) was properly defined
  const sess = await createBotSess();
  let job1: CronJob;
  let job2: CronJob;

  job1 = new CronJob('0 */1 * * * *', {
    command: 'updateVersionStatus',
    args: ['sess'],
  });

  job2 = new CronJob('0 */1 * * * *', 'updateVersionStatus(sess)');

标签: javascripttypescriptcron

解决方案


推荐阅读