🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@fluojs/cron

Package Overview
Dependencies
Maintainers
1
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@fluojs/cron

Decorator-based task scheduling for Fluo with cron, interval, and timeout triggers and optional distributed locking.

latest
Source
npmnpm
Version
2.0.1
Version published
Weekly downloads
29
-85.05%
Maintainers
1
Weekly downloads
 
Created
Source

@fluojs/cron

English 한국어

Decorator-based scheduling for fluo applications with lifecycle-managed startup/shutdown and optional Redis distributed locking.

Table of Contents

Installation

npm install @fluojs/cron

@fluojs/cron owns croner as a runtime dependency, so consumers do not need to install the scheduler engine directly.

@fluojs/redis is needed only when Redis distributed locking is enabled. Non-distributed scheduling paths do not load the Redis integration during package import, module registration, bootstrap, or status snapshot creation.

When to Use

  • When you need to run periodic background tasks (e.g., database cleanup, report generation).
  • When you want to schedule tasks using standard Cron expressions.
  • When running in a multi-instance environment and you need to ensure a task runs only on one instance at a time (Distributed Locking).
  • When you need simple one-off delayed tasks (Timeout) or fixed-rate intervals.

Quick Start

Register the CronModule and use decorators to schedule your methods.

Use CronModule.forRoot(...) to register scheduling for an application module. Cron expressions may use either five fields (minute hour day month weekday) or six fields (second minute hour day month weekday). The built-in CronExpression presets use six-field expressions when sub-minute precision is needed. Cron tasks start only after application bootstrap, dynamically registered cron tasks start when added to a started registry, and fluo forwards timezone plus no-overlap protection to the scheduler so one task instance does not overlap itself.

Scheduling decorators apply to public instance methods only. Do not migrate NestJS private scheduled methods, static helpers, or method names that are hidden behind legacy decorator metadata assumptions as-is; expose a public provider/controller method and keep any private implementation details behind that method. Explicit decorator name values must be non-empty strings, matching the dynamic registry validation contract.

import { Module } from '@fluojs/core';
import { CronModule, Cron, CronExpression, Interval, Timeout } from '@fluojs/cron';

class BillingService {
  @Cron(CronExpression.EVERY_MINUTE, { name: 'billing.reconcile' })
  async reconcilePendingInvoices() {
    console.log('Reconciling invoices...');
  }

  @Interval(15_000) // 15 seconds
  async pollStatus() {
    console.log('Polling status...');
  }

  @Timeout(5_000) // 5 seconds after startup
  async initialSync() {
    console.log('Running initial sync...');
  }
}

@Module({
  imports: [CronModule.forRoot()],
  providers: [BillingService],
})
class AppModule {}

Common Patterns

Migrating NestJS Cron Options

NestJS @Cron() options are not a drop-in CronTaskOptions object. Rename NestJS timeZone to fluo timezone:

// NestJS
@Cron('0 9 * * *', { timeZone: 'Asia/Seoul', waitForCompletion: true })

// fluo
@Cron('0 9 * * *', { timezone: 'Asia/Seoul' })

Do not copy waitForCompletion or invent an overlap flag. fluo does not expose either option: every cron task uses scheduler-level no-overlap protection plus an in-process running guard. If another tick arrives while the same task instance is still running, fluo skips that tick instead of queueing another run. A NestJS task with waitForCompletion: true therefore omits the option when migrated. If the NestJS task left waitForCompletion unset or set it to false and intentionally depended on overlapping runs, redesign that work behind an application-owned queue or worker rather than expecting fluo to enable overlap.

This guard covers one task instance in one application process. Use Distributed Locking when multiple application instances must not run the same task concurrently.

Distributed Locking

To prevent scheduled tasks from running concurrently across multiple server instances, enable distributed mode. This requires @fluojs/redis; the Redis peer is loaded and resolved only when distributed.enabled is true.

import { Module } from '@fluojs/core';
import { CronModule } from '@fluojs/cron';
import { RedisModule } from '@fluojs/redis';

@Module({
  imports: [
    RedisModule.forRoot({ host: 'localhost', port: 6379 }),
    CronModule.forRoot({
      distributed: {
        enabled: true,
        keyPrefix: 'fluo:cron:lock',
        lockTtlMs: 30_000,
      },
    }),
  ],
})
class AppModule {}

Leave distributed.clientName unset to keep using the default Redis registration above. To use a non-default Redis connection for distributed locks, set distributed.clientName to the name registered through RedisModule.forRoot({ name, ... }). fluo trims the configured client name during module option normalization and rejects blank values before lifecycle or status reporting uses the Redis dependency name.

distributed.lockTtlMs must stay at or above 1_000ms. When distributed locking is enabled, fluo validates that module-level TTL during option normalization before loading, resolving, or probing Redis. Task-level lockTtlMs overrides are validated only when module distributed mode and that task's distributed locking are both enabled. Disabled module or task locking does not fail solely because an inactive TTL is below the distributed minimum. fluo renews the Redis lock before the active TTL expires, including the minimum supported 1_000ms boundary.

Each scheduler instance uses a platform-neutral default distributed.ownerId; set distributed.ownerId explicitly only when your deployment has a stronger stable-owner convention. When distributed.ownerId is provided, fluo trims it during module option normalization and rejects blank or non-string values before scheduler or Redis lifecycle setup, so invalid or empty owner identifiers cannot enter Redis lock ownership state. Lock release runs in a finally path after task execution. If bootstrap later fails while a distributed tick is already running, startup rollback keeps the Redis lock client available until that active task can drain and release its lock. If Redis release fails, fluo keeps local ownership in status snapshots and retries during shutdown; if Redis reports that another owner holds the key, local ownership is cleared because fencing has already moved elsewhere. Redis TTL and renewal timing are still drift-sensitive coordination primitives rather than hard fencing tokens, so long-running jobs should remain idempotent and use application-level fencing when stale work would be unsafe.

@Module({
  imports: [
    RedisModule.forRoot({ host: 'localhost', port: 6379 }),
    RedisModule.forRoot({ name: 'locks', host: 'localhost', port: 6380 }),
    CronModule.forRoot({
      distributed: {
        clientName: 'locks',
        enabled: true,
        keyPrefix: 'fluo:cron:lock',
        lockTtlMs: 30_000,
      },
    }),
  ],
})
class MultiRedisCronModule {}

Dynamic Scheduling

You can manage tasks at runtime using the SCHEDULING_REGISTRY.

import { Inject } from '@fluojs/core';
import { SCHEDULING_REGISTRY, type SchedulingRegistry } from '@fluojs/cron';

@Inject(SCHEDULING_REGISTRY)
class TaskManager {
  constructor(private readonly registry: SchedulingRegistry) {}

  addNewTask() {
    this.registry.addCron('dynamic-job', '0 * * * *', () => {
      console.log('Dynamic job running!');
    });
  }

  speedUpPolling() {
    this.registry.updateIntervalMs('inventory.poll', 5_000);
  }

  stopTask() {
    this.registry.remove('dynamic-job');
  }
}

The registry exposes addCron, addInterval, addTimeout, remove, enable, disable, get, getAll, updateCronExpression, and updateIntervalMs. The first name argument is the default registry key; passing options.name overrides the actual registry key, scheduler metadata name, and default distributed lock key for dynamic tasks so dynamic registration matches decorator naming semantics. Registry, decorator, and dynamic options.name task names must be non-empty strings; blank dynamic override names are rejected before scheduler or registry state is retained. get and getAll return immutable SchedulingTaskDescriptor snapshots, not live CronJob handles or mutable registry state. Timeout tasks run once, then disable themselves while remaining in the registry so they can be re-enabled deliberately.

Dynamic cron registration is atomic with scheduler startup: if the scheduler rejects a new cron job, the registry does not retain a half-registered task. Updating a running cron expression or interval cadence is also rollback-safe. A replacement is committed only after the previous scheduled handle stops successfully. If replacement scheduling fails or the previous handle cannot be stopped, fluo stops the provisional replacement, restores the previous expression or interval milliseconds and handle, and rethrows the failure instead of silently retaining duplicate schedules. Cron tasks use both scheduler-level no-overlap protection and fluo's in-process running guard, so the same task instance will not run overlapping ticks.

Bounded Shutdown

CronModule drains active task executions during application shutdown with a bounded timeout so one hung task cannot block process termination forever.

By default the shutdown drain waits up to 10_000ms. If that timeout expires, the scheduler logs a warning and continues shutdown without waiting for the hung task to settle. The same shutdown.timeoutMs boundary also applies to Redis owned-lock release I/O during shutdown, so a stuck Redis release cannot block process termination indefinitely. When distributed locking is enabled, locks held by still-running tasks are not eagerly released on timeout; they remain owned by that task until it settles normally, or until Redis expires the lock after the process exits. fluo calls unref() on lock renewal timers so they continue renewing while other work keeps the Node.js event loop active without retaining the process by themselves, and it clears them when the task settles. If release I/O itself times out, fluo preserves local owned-lock visibility/status and does not clear ownership until Redis confirms release or reports that another owner holds the key. This prevents another node from starting the same job while the original task is still running.

@Module({
  imports: [
    CronModule.forRoot({
      shutdown: {
        timeoutMs: 5_000,
      },
    }),
  ],
})
class AppModule {}

Only singleton providers/controllers are scheduled. Request-scoped and transient scheduled classes are skipped with a warning.

Public API Overview

Modules

  • CronModule.forRoot(options): Configures the scheduler and enables distributed locking if requested.

Decorators

  • @Cron(expression, options?): Schedules a method using a cron expression.
  • @Interval(ms, options?): Schedules a method to run at a fixed interval.
  • @Timeout(ms, options?): Schedules a method to run once after a delay.

Constants & Tokens

  • CronExpression: Enum-like object with common cron patterns, including sub-minute presets such as EVERY_SECOND, EVERY_5_SECONDS, and EVERY_30_SECONDS.
  • SCHEDULING_REGISTRY: Injection token for the SchedulingRegistry service.
  • normalizeCronModuleOptions(...): Normalizes module options and defaults.
  • createCronPlatformStatusSnapshot(...): Creates a status snapshot for health/readiness integrations.
  • Public scheduling types: SchedulingTaskKind, SchedulingTaskCallback, SchedulingTaskOptions, CronTaskOptions, IntervalTaskOptions, TimeoutTaskOptions, CronTaskMetadata, IntervalTaskMetadata, TimeoutTaskMetadata, SchedulingTaskMetadata, CronTaskDescriptor, SchedulingTaskDescriptor, and SchedulingRegistry.
  • Public module and scheduler types: CronModuleOptions, NormalizedCronModuleOptions, CronDistributedOptions, CronShutdownOptions, CronScheduleOptions, CronScheduler, and CronScheduledJob.
  • Public status types: CronLifecycleState, CronStatusAdapterInput, and CronPlatformStatusSnapshot.
  • Metadata helpers and symbols: defineSchedulingTaskMetadata, defineCronTaskMetadata, getSchedulingTaskMetadata, getCronTaskMetadata, getSchedulingTaskMetadataEntries, getCronTaskMetadataEntries, schedulingMetadataSymbol, cronMetadataSymbol.
  • @fluojs/redis: Required for distributed locking functionality.
  • @fluojs/core: Required for DI and Module management.
  • croner: The underlying scheduling engine.

Example Sources

  • packages/cron/src/module.test.ts: Comprehensive tests for decorators and module lifecycle.
  • packages/cron/src/service.ts: Runtime scheduling, registry, and shutdown behavior.
  • packages/cron/src/status.test.ts: Status snapshot behavior.
  • packages/cron/src/distributed-lock-manager.ts: Redis distributed lock behavior.

Keywords

fluo

FAQs

Package last updated on 14 Jul 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts