Task Scheduler in TypeScript: Complete Guide
A task scheduler is a tool that allows you to run functions or scripts at a specific time or at a given interval. In the TypeScript ecosystem, there are several mature libraries for implementing such scenarios: from simple timers to powerful cron systems. In this article, we will break down the main approaches and show how to use them in real projects.
Why do you need a task scheduler?
Automating repetitive actions is a key task for any server application. Typical scenarios:
- Sending email notifications every hour.
- Cleaning up temporary files every night.
- Collecting analytics at the end of the day.
- Updating the cache on a schedule.
TypeScript (and JavaScript) has a built-in basic mechanism — setInterval and setTimeout, but for complex schedules it is more convenient to use specialized libraries.
Built-in tools: setInterval and setTimeout
The simplest way is to use global functions:
// Example: run every 5 secondsconst intervalId = setInterval(() => { console.log('Task executed at', new Date().toISOString());}, 5000);
// Stop after 30 secondssetTimeout(() => { clearInterval(intervalId); console.log('Scheduler stopped');}, 30000);Pros: no installation required, works in any environment. Cons: no support for cron expressions, difficult to manage missed tasks.
node-cron library
One of the most popular libraries for Node.js. It works with the classic cron format (5 fields): minutes, hours, day of month, month, day of week.
Installation
npm install node-cronnpm install @types/node-cronUsage example
import * as cron from 'node-cron';
// Task: every minutecron.schedule('* * * * *', () => { console.log('Running every minute');});
// Task: every day at 9:30 AMcron.schedule('30 9 * * *', () => { console.log('Daily task at 9:30');});
// Task: weekdays at 6:00 PMcron.schedule('0 18 * * 1-5', () => { console.log('Weekdays at 6:00 PM');});Task management
import * as cron from 'node-cron';
const task = cron.schedule('*/5 * * * *', () => { console.log('Every 5 minutes');});
// Stop the tasktask.stop();
// Resumetask.start();
// Check statusconsole.log(task.isActive()); // true or falsecroner library
A more modern alternative, written from scratch in TypeScript. It supports extended syntax (seconds, month names) and works both in Node.js and the browser.
Installation
npm install cronerExample with seconds
import Cron from 'croner';
// Every 10 secondsconst job = new Cron('*/10 * * * * *', () => { console.log('Running every 10 seconds');});
// Task: every Monday at 8:30 AMconst weeklyJob = new Cron('30 8 * * 1', () => { console.log('Monday, 8:30 AM');});
// Stop after 1 minutesetTimeout(() => { job.stop(); console.log('Task stopped');}, 60000);Advanced features
import Cron from 'croner';
// Task with a name and timezoneconst job = new Cron('0 9 * * *', { name: 'morning-report', timezone: 'Europe/Moscow'}, () => { console.log('Morning report for Moscow');});
// Get the next execution timeconst nextRun = job.nextRun();console.log('Next run:', nextRun.toISOString());
// List all active jobsconst activeJobs = Cron.getJobs();console.log('Active jobs:', activeJobs.length);Comparison of node-cron and croner
- node-cron — a time-tested library
Also in library
Monitoring Rust Applications: tracing Library and Metrics
Observation Swift: Complete Guide with Examples
GraphQL for C# (.NET): Complete Guide to the GraphQL.NET Library
Working with Markdown in Node.js: Libraries and Tools for Conversion