Skip to content

Cron Jobs

Cron job allows you to execute something on a schedule.

Getting Started

Create a new file in stack9/cron-jobs called example-cron-job.js

@prop context - object - context

// stack9/cron-jobs/example-cron-job.ts`
module.exports = {
  exec: context => {
    const { services, logger, db } = context;

    return {
      success: true,
      message: `Something went right`,
    };
  },
  timeout: 5000,
};

or in TypeScript

import { CronJobFunction } from "@april9/stack9-sdk"

// stack9/server/cron-jobs/example-cron-job.ts`
class ExampleCronJob extends CronJobFunction {
  constructor(private context: CronJobContext) {
    super();
  }
  async exec(): Promise<CronJobResponse> {
    const { services, logger, db } = this.context;

    // ...

    return {
      success: true,
      message: `Something went right`,
    };
  }
}

export default withCronJob(ExampleCronJob, 5000);

Register your cron

Register the cronjob function and the interval it should run.

@prop command - string - should match the filename without extension.
@prop cronTime - string - represents the interval your cronjob function should run. It could be simple like the next example to run every second, or much ore complex. read more

stack9/app.json

{
  "cronJobs": [
    {
      "command": "example-cron-job",
      "cronTime": "*/30 * * * * *"
    }
  ]
}