Skip to content

Repository files navigation

@useschedo/node

npm version License: MIT

The official Node.js SDK for Schedo, a job scheduling and execution management service.

Installation

npm install @useschedo/node
# or
yarn add @useschedo/node
# or
pnpm add @useschedo/node

Quick Start

import {
  SchedoSDK,
  ExecutionInterval,
  withApiKey,
  withBaseURL,
} from "@useschedo/node";

async function main() {
  // Initialize the SDK with your API key
  const sdk = new SchedoSDK(
    withApiKey("YOUR_API_KEY"),
  );

  // Define a job that runs every minute
  await sdk.defineJob(
    "example_job",
    ExecutionInterval.EveryMinute,
    async (ctx) => {
      console.log("Executing job...");
      return "Job completed successfully";
    },
  );

  // Start listening for job execution events
  sdk.start();

  // Keep the process running
  setInterval(() => {}, 1000 * 60);
}

main().catch(console.error);

Core Concepts

The Schedo SDK allows you to define jobs with specific schedules and execute them when triggered. The main components are:

  • SchedoSDK: The main class for job scheduling and execution management
  • Jobs: Tasks defined with a name, schedule, and execution function
  • Executors: Functions that run when a job is triggered
  • Execution Context: Context object available to executors containing job metadata and utilities

Detailed Usage

Initializing the SDK

import { SchedoSDK, withApiKey, withBaseURL, withVerbose } from "@useschedo/node";

const sdk = new SchedoSDK(
  withApiKey("YOUR_API_KEY"),
  withVerbose(true), // Optional: enables verbose logging
);

Scheduling Jobs

import { ExecutionInterval, withTimeout, withMetadata, withBlocking } from "@useschedo/node";

// Define a job with a cron expression
await sdk.defineJob(
  "cron_job_example",
  "0 9 * * 1-5", // Runs at 9 AM on weekdays
  async (ctx) => {
    console.log("Running weekday morning job");
    return { status: "success" };
  },
  withTimeout(30), // Optional: 30 second timeout
  withMetadata({ category: "reports" }), // Optional: adds metadata to the job
  withBlocking(true), // Optional: makes job execution blocking
);

// Define a job with predefined intervals
await sdk.defineJob(
  "interval_job_example",
  ExecutionInterval.Hourly,
  async (ctx) => {
    console.log("Running hourly job");
    const { metadata } = ctx;
    return { processedAt: new Date().toISOString() };
  }
);

Available Execution Intervals

The SDK provides convenient constants for common execution intervals:

import { ExecutionInterval } from "@useschedo/node";

ExecutionInterval.EveryMinute  // "* * * * *"
ExecutionInterval.Hourly       // "0 * * * *"
ExecutionInterval.Daily        // "0 0 * * *"
ExecutionInterval.Weekly       // "0 0 * * 0"
ExecutionInterval.Monthly      // "0 0 1 * *"

Working with Execution Context

Every job executor receives a context object with useful information and utilities:

await sdk.defineJob(
  "context_example",
  ExecutionInterval.Daily,
  async (ctx) => {
    // Access job metadata
    const { metadata } = ctx;

    // Access execution info
    console.log(`Executing job: ${ctx.jobCode}`);
    console.log(`Execution ID: ${ctx.executionId}`);

    // Perform job work...

    return { completed: true, timestamp: new Date().toISOString() };
  },
  withMetadata({ owner: "analytics-team", priority: "high" })
);

Starting and Stopping the SDK

// Start listening for job execution events
sdk.start();

// Stop listening for job execution events
sdk.stop();

Configuration Options

SDK Options

Option Function Description Default
API Key withApiKey(key) Sets the API key for authentication Required
Verbose withVerbose(boolean) Enables verbose logging false

Job Definition Options

Option Function Description Default
Blocking withBlocking(boolean) Sets whether job execution should block false
Metadata withMetadata(object) Sets metadata for the job {}
Timeout withTimeout(seconds) Sets timeout duration in seconds 0

Error Handling

The SDK automatically handles many types of errors, including:

  • Job execution timeouts
  • Executor failures
  • Network and connection issues
try {
  await sdk.defineJob(
    "error_handling_example",
    ExecutionInterval.Daily,
    async (ctx) => {
      // This job might fail
      if (Math.random() > 0.5) {
        throw new Error("Random failure");
      }
      return { success: true };
    },
    withTimeout(5) // Set a 5-second timeout
  );
} catch (error) {
  console.error("Failed to define job:", error);
}

Advanced Usage

Custom Error Handling

await sdk.defineJob(
  "custom_error_handler",
  ExecutionInterval.Hourly,
  async (ctx) => {
    try {
      // Attempt to perform work
      const result = await performRiskyOperation();
      return { success: true, result };
    } catch (error) {
      // Log error details and return formatted error
      console.error("Operation failed:", error);
      return { success: false, error: error.message };
    }
  }
);

License

MIT

About

The official Node.js SDK for Schedo, a job scheduling and execution management service.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages