cron#CronTime TypeScript Examples

The following examples show how to use cron#CronTime. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LocalTaskWorker.ts    From backstage with Apache License 2.0 6 votes vote down vote up
/**
   * Sleeps until it's time to run the task again.
   */
  private async waitUntilNext(
    settings: TaskSettingsV2,
    lastRunMillis: number,
    signal?: AbortSignal,
  ) {
    if (signal?.aborted) {
      return;
    }

    const isCron = !settings.cadence.startsWith('P');
    let dt: number;

    if (isCron) {
      const nextRun = +new CronTime(settings.cadence).sendAt().toJSDate();
      dt = nextRun - Date.now();
    } else {
      dt =
        Duration.fromISO(settings.cadence).as('milliseconds') - lastRunMillis;
    }

    dt = Math.max(dt, 0);

    this.logger.debug(
      `task: ${this.taskId} will next occur around ${DateTime.now().plus(
        Duration.fromMillis(dt),
      )}`,
    );

    await this.sleep(Duration.fromMillis(dt), signal);
  }
Example #2
Source File: types.ts    From backstage with Apache License 2.0 6 votes vote down vote up
function isValidCronFormat(c: string | undefined): boolean {
  try {
    if (!c) {
      return false;
    }
    // parse cron format to ensure it's a valid format.
    // eslint-disable-next-line no-new
    new CronTime(c);
    return true;
  } catch {
    return false;
  }
}
Example #3
Source File: cron-job.ts    From malagu with MIT License 6 votes vote down vote up
start() {
        if (this.running) {
            return;
        }

        this.tickDisposable = this.clock.onTick(async () => {

            const cronTime: CronTime = (this as any).cronTime;
            const timeout = cronTime.getTimeout();
            if (timeout <= 60 * 1000) {
                await this.fireOnTickAsync();
            }

        });
    }
Example #4
Source File: TaskWorker.ts    From backstage with Apache License 2.0 5 votes vote down vote up
/**
   * Perform the initial store of the task info
   */
  async persistTask(settings: TaskSettingsV2) {
    // Perform an initial parse to ensure that we will definitely be able to
    // read it back again.
    taskSettingsV2Schema.parse(settings);

    const isCron = !settings?.cadence.startsWith('P');

    let startAt: Knex.Raw;
    if (settings.initialDelayDuration) {
      startAt = nowPlus(
        Duration.fromISO(settings.initialDelayDuration),
        this.knex,
      );
    } else if (isCron) {
      const time = new CronTime(settings.cadence)
        .sendAt()
        .minus({ seconds: 1 }) // immediately, if "* * * * * *"
        .toUTC()
        .toISO();
      startAt = this.knex.client.config.client.includes('sqlite3')
        ? this.knex.raw('datetime(?)', [time])
        : this.knex.raw(`?`, [time]);
    } else {
      startAt = this.knex.fn.now();
    }

    this.logger.debug(`task: ${this.taskId} configured to run at: ${startAt}`);

    // It's OK if the task already exists; if it does, just replace its
    // settings with the new value and start the loop as usual.
    await this.knex<DbTasksRow>(DB_TASKS_TABLE)
      .insert({
        id: this.taskId,
        settings_json: JSON.stringify(settings),
        next_run_start_at: startAt,
      })
      .onConflict('id')
      .merge(['settings_json']);
  }
Example #5
Source File: TaskWorker.ts    From backstage with Apache License 2.0 5 votes vote down vote up
async tryReleaseTask(
    ticket: string,
    settings: TaskSettingsV2,
  ): Promise<boolean> {
    const isCron = !settings?.cadence.startsWith('P');

    let nextRun: Knex.Raw;
    if (isCron) {
      const time = new CronTime(settings.cadence).sendAt().toUTC().toISO();
      this.logger.debug(`task: ${this.taskId} will next occur around ${time}`);
      nextRun = this.knex.client.config.client.includes('sqlite3')
        ? this.knex.raw('datetime(?)', [time])
        : this.knex.raw(`?`, [time]);
    } else {
      const dt = Duration.fromISO(settings.cadence).as('seconds');
      this.logger.debug(
        `task: ${this.taskId} will next occur around ${DateTime.now().plus({
          seconds: dt,
        })}`,
      );
      nextRun = this.knex.client.config.client.includes('sqlite3')
        ? this.knex.raw(
            `max(datetime(next_run_start_at, ?), datetime('now'))`,
            [`+${dt} seconds`],
          )
        : this.knex.raw(
            `greatest(next_run_start_at + interval '${dt} seconds', now())`,
          );
    }

    const rows = await this.knex<DbTasksRow>(DB_TASKS_TABLE)
      .where('id', '=', this.taskId)
      .where('current_run_ticket', '=', ticket)
      .update({
        next_run_start_at: nextRun,
        current_run_ticket: this.knex.raw('null'),
        current_run_started_at: this.knex.raw('null'),
        current_run_expires_at: this.knex.raw('null'),
      });

    return rows === 1;
  }