Introduction
Cron tasks allow scripts to execute automatically at defined intervals, which is essential for backups, reports, or maintenance. In 2026, their integration with Node.js provides greater flexibility for modern applications. This intermediate tutorial guides you step by step to build reliable jobs, from system crontab through to node-cron implementation. You will learn error management, logging, and scalability. Proper mastery prevents silent failures and optimizes server resources.
Prerequisites
- Node.js 20+
- Basic knowledge of TypeScript
- Access to a Linux server or WSL
- npm or pnpm installed
Installing node-cron
npm install node-cron
npm install --save-dev @types/node-cronThis command installs the node-cron package to manage scheduled tasks directly in Node.js, along with TypeScript types for safe development.
Basic Cron Job Configuration
import cron from 'node-cron';
cron.schedule('0 2 * * *', () => {
console.log('Exécution de la sauvegarde quotidienne à 2h');
// Backup logic here
}, {
scheduled: true,
timezone: "Europe/Paris"
});This code schedules a task every day at 2 a.m. using the French timezone. The scheduled flag activates the job immediately.
Adding Error Handling
import cron from 'node-cron';
cron.schedule('0 2 * * *', async () => {
try {
await performBackup();
console.log('Sauvegarde réussie');
} catch (error) {
console.error('Erreur backup:', error);
// Send Slack or email alert
}
}, { timezone: "Europe/Paris" });Using try/catch prevents silent crashes and enables integration of notifications on failure.
Creating a Configuration File
export const cronConfig = {
backup: '0 2 * * *',
report: '0 9 * * 1',
cleanup: '0 4 * * 0'
} as const;Centralizing cron expressions in a config file simplifies maintenance and avoids duplication errors.
Advanced Cleanup Job
import cron from 'node-cron';
import { cleanupOldFiles } from '../utils/files';
cron.schedule(cronConfig.cleanup, async () => {
const deleted = await cleanupOldFiles(30);
console.log(`${deleted} fichiers supprimés`);
}, { timezone: "Europe/Paris" });This weekly job deletes files older than 30 days, demonstrating a concrete and reusable maintenance task.
Best Practices
- Always define an explicit timezone
- Use structured logs with job identifiers
- Limit task execution duration
- Test jobs in a staging environment
- Monitor with tools like PM2 or Datadog
Common Errors to Avoid
- Forgetting async error handling (silent jobs)
- Using invalid cron expressions without validation
- Failing to isolate long-running tasks that block the event loop
- Ignoring permissions on files executed by cron
Going Further
Explore advanced scalability and monitoring patterns in our Learni courses.