0

By bi-weekly I mean every two weeks.

I have a job I'd like to run every two weeks on Saturdays at 4:30pm and I'm using NestJs's @Cron decorator to specify when it runs.

Is there a simple way to specify intervals of two weeks from a specific start date?

import { Injectable, Logger } from '@nestjs/common';
import { Cron} from '@nestjs/schedule';

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

  _called = 0;

  @Cron('* * * * * sat')
  handleBiWeekly(): void {
    this.scrapeContestData();
  }

  scrapeContestData(): void {
    this._called += 1;
  }
}

These two test cases need to pass:

import { INestApplication } from '@nestjs/common';
import { ScheduleModule } from '@nestjs/schedule';
import { Test } from '@nestjs/testing';
import { AppModule } from '../app.module';
import { TasksModule } from './tasks.module';
import { TasksService } from './tasks.service';
import * as sinon from 'sinon';

describe('TasksService', () => {
  let app: INestApplication;
  let clock: sinon.SinonFakeTimers;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      imports: [
        {
          module: AppModule,
          imports: [ScheduleModule.forRoot(), TasksModule],
          providers: [TasksService],
        },
      ],
    }).compile();

    app = module.createNestApplication();
  });

describe('biweekly', () => {
    test('Feb 19 at 4:30 PM, scrapeContestData TO BE called', async () => {
      const service = app.get(TasksService);
      clock = sinon.useFakeTimers({
        now: new Date('2022-02-19T16:30Z').valueOf(),
      });
      await app.init();
      clock.tick(3000);
      expect(new Date().getDay()).toBe(6);
      expect(service._called).toBe(3);
    });

     test('a week after Feb 19 at 4:30PM, scrapeContestData to NOT BE called', async () => {
      const service = app.get(TasksService);
      clock = sinon.useFakeTimers({
        now: new Date('2022-02-26T16:30Z').valueOf(),
      });
      await app.init();
      clock.tick(3000);
      expect(new Date().getDay()).toBe(6);
      expect(service._called).toBe(0);
    });
});
Dozie
  • 103
  • 11
  • I'm sorry, what exactly do you need? Just to make the tests to pass or a cron expression that runs each 2 weeks? – Lucas Feb 16 '22 at 23:41
  • @Lucas I'm more interested in making the tests pass. Just assumed a cron expression that runs every 2 weeks will be the best way to do that. – Dozie Feb 17 '22 at 11:53

0 Answers0