Skip to content

Runner Module

This file defines the Runner class, which is responsible for managing and executing all tasks decorated with the @Task decorator in the @sodacore/core library. It creates cron jobs for scheduled tasks and provides lifecycle methods to initialize, start, and stop all tasks.


Features

  • Task Discovery: Finds all registered tasks in the global Registry that are decorated as tasks.
  • Cron Scheduling: Uses the Croner library to schedule and run tasks based on their cron patterns.
  • Manual Tasks: Supports tasks that are set to run manually (not scheduled).
  • Lifecycle Management: Provides methods to initialize, start, and stop all tasks.

Usage

typescript
import Runner from './module/runner';

const runner = new Runner(config);
await runner.init();
await runner.start();
// ... later
await runner.stop();

API

Properties

  • manualTasks: BaseTask[] List of tasks that are set to run manually (schedule is 'manual').
  • tasks: Cron[] List of active cron jobs for scheduled tasks.

Methods

async init(): Promise<void>

Initializes the runner module:

  • Discovers all registered tasks.
  • Initializes each task by calling its init method.
  • Creates cron jobs for tasks with a schedule (other than 'manual').
  • Adds manual tasks to the manualTasks array.

async start(): Promise<void>

Starts all scheduled tasks by resuming their cron jobs.

async stop(): Promise<void>

Stops all scheduled tasks by stopping their cron jobs.


How It Works

  1. Task Discovery:

    • Filters all modules in the Registry to find those with the type metadata set to 'task'.
  2. Initialization:

    • Calls init() on each discovered task.
    • For each task, retrieves its schedule and user-defined options from metadata.
    • If the schedule is 'manual', adds the task to manualTasks.
    • Otherwise, creates a new cron job using the Croner library and adds it to tasks.
  3. Lifecycle:

    • start() resumes all cron jobs, starting scheduled execution.
    • stop() stops all cron jobs, halting scheduled execution.

Notes

  • Tasks must extend BaseTask and be decorated with the @Task decorator to be managed by the runner.
  • Manual tasks are not scheduled and must be triggered manually.
  • The runner logs initialization, starting, and stopping of tasks for traceability.

Released under the Apache-2.0 License.