Docs for the next release (prerelease). Install it with npm i @meghjs/cli@next. Latest release docs →

Next release (prerelease) · Latest docs →

Skip to content

Scheduler ​

Run code on a schedule with decorators. Mark a class with @ScheduledTask(), then decorate its methods with @Cron, @Interval or @Timeout.

Cron support comes from node-cron, which is installed with @meghjs/core.

Generate one

npx megh make:task CleanupTokens --cron "0 3 * * *" writes a task class to fill in. See Generators.

A task class ​

ts
import { Cron, Interval, ScheduledTask, Timeout } from '@meghjs/core';
import { ReportService } from '../services/report.service';
import { CacheWarmer } from '../services/cache-warmer.service';

@ScheduledTask()
export class ReportTask {
  constructor(
    private readonly reports: ReportService,
    private readonly cache: CacheWarmer,
  ) {}

  @Cron('0 8 * * 1-5', { timezone: 'Asia/Dhaka' }) // 08:00 on weekdays
  async sendDailyReport() {
    await this.reports.sendDaily();
  }

  @Interval(60_000) // every minute
  async pollPending() {
    await this.reports.processPending();
  }

  @Timeout(5_000) // once, 5 seconds after startup
  async warmCache() {
    await this.cache.warmUp();
  }
}

@ScheduledTask() takes parentheses. A class can have any number of scheduled methods, and one method can carry several decorators.

Registering tasks ​

Pass the classes to useScheduler:

ts
import { Megh } from '@meghjs/core';
import { ReportTask } from './tasks/report.task';

const app = Megh.createApplication();
app.useScheduler([ReportTask]);

Or scan a folder:

ts
app.useScheduler({ path: 'src/tasks' });

The scan works like controller auto-discovery:

  • src/tasks is the conventional folder.
  • Subfolders are scanned too. Files ending in .test, .spec or .e2e-spec are skipped.
  • Every exported class marked with @ScheduledTask() is registered. Other exports are ignored.
  • In a compiled app, the tsconfig rootDir (default src) is swapped for its outDir (default dist) and .js files are loaded. When TypeScript runs directly (ts-node, tsx), the .ts files in src are loaded. An absolute path is used as-is.
  • useScheduler({}) and useScheduler() scan src/tasks.
  • A missing folder logs a warning and the app starts without those tasks. A file that fails to import stops startup.

A class registered in the list and found by the scan runs once, not twice. Two different classes with the same name, in different files, both run.

Decorators ​

DecoratorRuns
@Cron(expression, options?)On a cron expression
@Interval(ms, options?)Every ms milliseconds, first run after ms
@Timeout(ms, options?)Once, ms milliseconds after the scheduler starts

The expression is a 5-field cron string, or 6 fields with seconds first:

ts
@Cron('0 0 * * *')          // midnight every day
@Cron('*/5 * * * *')        // every 5 minutes
@Cron('*/10 * * * * *')     // every 10 seconds

Options ​

All three decorators take:

OptionDefaultDescription
nameClassName#methodName shown in logs. Also identifies the job between replicas
disabledfalseSkip this job. It is logged as disabled and never runs
perInstancefalseRun on every replica. See Multiple replicas. Ignored by @Timeout

@Cron also takes:

OptionDefaultDescription
timezoneserver timeIANA zone, such as 'Asia/Dhaka' or 'Europe/London'
runOnInitfalseAlso run once when the scheduler starts

The option types are exported as BaseJobOptions and CronOptions, so you can build options outside the decorator:

ts
import type { CronOptions } from '@meghjs/core';

const nightly: CronOptions = { timezone: 'Europe/London', name: 'nightly' };

disabled is handy for feature flags:

ts
@Cron('0 3 * * *', { disabled: process.env.NIGHTLY_CLEANUP !== 'true' })
async cleanup() { ... }

Dependency injection ​

Task classes are resolved through dependency injection, so constructor parameters and inject() both work. Each class is built once when the scheduler starts, and that instance is shared with the rest of the app.

ts
@ScheduledTask()
export class CleanupTask {
  private readonly sessions = inject(SessionService);

  @Cron('0 * * * *')
  async purge() {
    await this.sessions.deleteExpired();
  }
}

Scheduled methods are inherited. A subclass can override one by redeclaring the method with the same kind of decorator (@Cron, @Interval or @Timeout).

When tasks run ​

Tasks start inside app.run(), after the onInit hooks (so MeghORM is connected) and after routes are mapped, but before the server listens. They stop in app.close(), right after the HTTP server stops. See Application for the full order.

This means:

  • @Timeout(0) and runOnInit jobs can run before the server accepts requests and before onReady.
  • Nothing runs if you never call run(), for example in tests.
  • close() stops new runs and waits for a job that is in the middle of running. On SIGTERM/SIGINT that wait counts toward shutdownTimeout, so very long jobs can still be cut off.
  • If startup fails after the tasks started (an error in app.ready(), the port already in use), they are stopped before run() rejects.

An invalid cron expression throws when the scheduler starts, so run() fails with Invalid cron expression "..." on ReportTask#sendDailyReport.

Errors and overlapping runs ​

A job that throws or rejects is logged at error level and keeps its schedule. It never crashes the process. Logs go through the logger:

[Megh Scheduler] Error in "ReportTask#sendDailyReport": SMTP timeout

If a run is still going when the next one is due, the new run is skipped with a warning. A slow @Interval(1000) job never runs twice at once.

Handle errors you care about inside the job, for example to alert or retry.

Multiple replicas ​

With several replicas, a @Cron or @Interval job runs once per tick across all of them, not once per replica. Before a run, each replica tries to take a lock for that tick. One gets it and runs the job; the others skip it.

The lock lives in the first of these that is available:

  1. Redis, when messaging runs on the redis transport (app.useMessaging({ transport: 'redis' }), or just MEGH_MESSAGING_TRANSPORT=redis in the environment);
  2. the megh_locks table, when Megh ORM is connected and the table exists (npx megh make:messaging, then npx megh migrate);
  3. memory, which only works within one process. In production Megh logs a warning, since every replica then runs every job.

Replicas recognise the same job by its name, or ClassName#method without one. Keep it the same across replicas.

For a job that should run on every replica, such as clearing a local cache, pass perInstance: true:

ts
@Interval(60_000, { perInstance: true })
async clearLocalCache() {
  this.cache.clear();
}

@Timeout jobs always run on each instance: they belong to that process's startup.

The lock picks one replica per tick; it does not make the work itself safe to repeat. If a job must never run twice, for example to charge customers, also make it idempotent, or have it push work onto a queue with a fixed jobId, such as the date, via dispatch(name, data, 0, { jobId }). On Redis, a job whose ID already exists is ignored.

See Deployment for running replicas.

MeghScheduler ​

useScheduler is enough for most apps. MeghScheduler is the class behind it, for running tasks in a process without the HTTP app, such as a dedicated scheduler container:

ts
import { MeghScheduler } from '@meghjs/core';
import { ReportTask } from './tasks/report.task';
import { CleanupTask } from './tasks/cleanup.task';

const scheduler = new MeghScheduler();
scheduler.addTaskClasses([ReportTask, CleanupTask]);
scheduler.start();

const stop = async () => {
  await scheduler.stopAll(); // waits for runs in progress
  process.exit(0);
};
process.once('SIGTERM', stop);
process.once('SIGINT', stop);
MethodDescription
addTaskClasses(classes)Add task classes. Adding the same class again is ignored
start()Build each class and start its jobs. Call it once
stopAll()Stop every job. Returns a promise that resolves when runs in progress finish
setLockStore(store)Use this LockStore for tick locks instead of choosing one: MemoryLockStore, DatabaseLockStore, or your own { name, acquire(key, ttlMs, owner) }

Outside app.run() there are no lifecycle hooks, so anything the tasks need, such as a database connection, must be set up before start(). A class without @ScheduledTask() is skipped with a warning.

Released under the MIT License.