Skip to main content

Overview

Balda.js includes a cron job decorator that lets you schedule background tasks directly from your controllers or services. This feature is available only in Node.js compatible environments.

Peer dependency — Balda.js intentionally leaves the scheduling engine to the community-standard node-cron. To enable cron support you must install it yourself:

# with npm
npm install node-cron

# or with yarn / pnpm / bun
yarn add node-cron
pnpm add node-cron
bun add node-cron

Basic Usage

import { cron } from 'balda-js';

class TickCron {
// Run every minute
@cron('* * * * *')
async handle() {
console.log('Cron executed!');
}
}

The decorator accepts any valid cron expression supported by node-cron.

Advanced Options

You can pass an options object as the second argument to control timezone, concurrency, etc.

@cron('0 0 * * *', { timezone: 'UTC' })
async handle() {
await this.cleanupService.run();
}

Error Handling

By default, if the decorated method throws, Balda.js will log the error (using the configured logger) but will not crash your server.

You can set a global cron error handler to handle the errors:

server.setGlobalCronErrorHandler((error) => {
console.error(error);
});

Starting Cron Jobs

You can import registered cron jobs classes that have one or more @cron decorated methods or directly import the @cron decorator and use it to decorate your own methods.

import './cron/specific_cron_job';

server.startRegisteredCrons(['./cron/cron_jobs.{ts,js}'], () => {
console.log('Cron jobs started');
});