This guide will help you set up your first cloud-based scheduled job using the Schedo Node.js SDK.
Prerequisites
Before you begin, make sure you have:
- A Schedo.dev account and API key
- Node.js 16.x or later installed
- A task you want to schedule (e.g., data processing, cleanup, notifications)
Installation
Install the Schedo.dev Node.js SDK using your preferred package manager:
# Using npm
npm install @useschedo/node
# Using pnpm
pnpm add @useschedo/node
# Using yarn
yarn add @useschedo/node
Create Your First Job
Create a new file called jobs.ts
(or jobs.js
if you’re not using TypeScript):
import {
SchedoSDK,
ExecutionInterval,
withApiKey,
withBaseURL,
} from "@useschedo/node";
// Initialize the SDK with your API key
const schedo = new SchedoSDK(withApiKey("YOUR_API_KEY"));
// Define a job that runs every day at midnight
try {
await schedo.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);
}
// Start the job listener
schedo.start();
// Graceful shutdown
process.on('SIGTERM', () => {
console.log('Shutting down...');
schedo.stop();
process.exit(0);
});
Understanding the Code
Let’s break down the key components:
-
SDK Initialization
import { SchedoSDK, withApiKey } from "@useschedo/node";
const schedo = new SchedoSDK(withApiKey(process.env.SCHEDO_API_KEY));
Connects your Node.js application to Schedo.dev’s cloud platform.
-
Job Definition
schedo.defineJob(
'daily-cleanup', // Unique job identifier
'0 0 * * *', // Run at midnight
async (ctx) => { // Job handler
// Job logic
});
Defines a job that Schedo.dev will execute according to the schedule.
-
Error Handling
try {
await operation();
} catch (error) {
await log('Operation failed', { error });
throw error; // Schedo handles retries automatically
}
Schedo.dev provides built-in error handling;
Running Your Job
-
Set your API key as an environment variable:
export SCHEDO_API_KEY=your_api_key_here
-
Run your job file:
# Using TypeScript
pnpm tsx jobs.ts
# Using Node.js
node jobs.js
Your job is now running in the cloud! Schedo.dev will:
- Execute it according to the schedule
- Prevent duplicate runs
- Provide logs and monitoring
TypeScript Support
The Schedo Node.js SDK is written in TypeScript and provides full type safety:
schedo.defineJob(
'typed-job',
'0 0 * * *',
async (ctx) => {
const result = await performCleanup();
return {
count: result.count,
duration: result.duration
};
}
);
Next Steps