javascript - passing variable from config service into Typescript decorator - Stack Overflow

I would like to create a scheduled task for my NestJs application. It should execute every X seconds so

I would like to create a scheduled task for my NestJs application. It should execute every X seconds so I use intervals as described here.

The application makes use of configuration files so I could use keep the interval configurable. But how would I pass in a variable to the Typescript decorator?

NestJs is providing a sample repository for scheduled tasks

So based on the sample I would like to have something like

@Injectable()
export class TasksService {
  constructor(
    private readonly myConfigService: MyConfigService,
  ) {}

  @Interval(this.myConfigService.intervalInMilliseconds)
  handleInterval() {
    // ...
  }
}

Do I have to use the SchedulerRegistry as described below in the docs? It seems this is not possible with standard Typescript, see this thread.

I would like to create a scheduled task for my NestJs application. It should execute every X seconds so I use intervals as described here.

The application makes use of configuration files so I could use keep the interval configurable. But how would I pass in a variable to the Typescript decorator?

NestJs is providing a sample repository for scheduled tasks

So based on the sample I would like to have something like

@Injectable()
export class TasksService {
  constructor(
    private readonly myConfigService: MyConfigService,
  ) {}

  @Interval(this.myConfigService.intervalInMilliseconds)
  handleInterval() {
    // ...
  }
}

Do I have to use the SchedulerRegistry as described below in the docs? It seems this is not possible with standard Typescript, see this thread.

Share Improve this question edited Jan 11, 2020 at 20:35 Kim Kern 60.7k20 gold badges218 silver badges214 bronze badges asked Jan 11, 2020 at 20:08 Question3rQuestion3r 3,87229 gold badges123 silver badges244 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

This is not possible with the declarative API (annotations), you have to register the cron job dynamically (see the docs):

@Injectable()
export class TasksService implements OnModuleInit {
  constructor(
    private readonly myConfigService: MyConfigService,
    private readonly schedulerRegistry: SchedulerRegistry,
  ) {}

  onModuleInit() {
    const interval = setInterval(() => this.handleInterval, this.myConfigService.intervalInMs);
    this.schedulerRegistry.addInterval('my-dynamic-interval', interval);
  }

  handleInterval() {
    // ...
  }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745286190a4620575.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信