madeindjs / nestjs-graphile-worker

A Nest.js wrapper for Graphile Worker
https://www.npmjs.com/package/nestjs-graphile-worker
MIT License
36 stars 14 forks source link

Do this integration supports Recurring tasks (crontab)? #25

Closed aguirrel closed 3 weeks ago

aguirrel commented 3 weeks ago

Hi guys,

I'm trying to schedule some recurring tasks for my project. It seems that graphile does support it but I can't find how could I integrate it using nestjs and nesstjs-graphile-worker package.

Could you guide me?

Thanks!

madeindjs commented 3 weeks ago

Hello @aguirrel ,

The crontab can be given in library mode using RunnerOption. We're using the runner option in the module configuration, so you should be able to do something like this

@Module({
  imports: [
    ConfigModule.forRoot(),
    GraphileWorkerModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      useFactory: (config: ConfigService) => ({
        connectionString: config.get('PG_CONNECTION'),
        // see syntax at https://worker.graphile.org/docs/cron#crontab-format
        crontab: [
          ' * * * * * taskIdentifier ?priority=1 {"foo": "bar"}',
        ].join('\n')
      }),
    }),
  ],
  controllers: [AppController],
  providers: [AppService, HelloTask],
})
export class AppModule {}

I never tested it though, I will be happy to have your feedback about it.


Alternatively, a simple solution is to rely on @nestjs/schedule instead. Something like

import { Injectable, Logger } from "@nestjs/common";
import { Cron } from "@nestjs/schedule";
import { WorkerService } from "nestjs-graphile-worker";

@Injectable()
export class TasksService {
  private readonly logger = new Logger(TasksService.name);

  constructor(private readonly graphileWorker: WorkerService) {}

  @Cron("45 * * * * *")
  async handleCron() {
    // create a job each hour at 45'
    await this.graphileWorker.addJob("hello", { hello: "world" });
    this.logger.debug("Called when the current second is 45");
  }
}

The drawback is, it's not a good solution when your service is replicated. You should use Graphile's CRON if so.

aguirrel commented 3 weeks ago

Hi @madeindjs ,

Using crontab inside the factory worked like a charm.

Thanks a lot!