• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

node-cron / node-cron / 16895283675

12 Aug 2025 12:08AM UTC coverage: 89.256% (-7.8%) from 97.037%
16895283675

Pull #481

github

web-flow
Merge 39584aad7 into c76f95e92
Pull Request #481: build: using rollout

457 of 540 branches covered (84.63%)

Branch coverage included in aggregate %.

4 of 4 new or added lines in 2 files covered. (100.0%)

161 existing lines in 11 files now uncovered.

1595 of 1759 relevant lines covered (90.68%)

37.31 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

88.89
/src/node-cron.ts
1
/**
1✔
2
 * Node Cron
1✔
3
 * 
1✔
4
 * A flexible cron-based task scheduling system that supports both inline functions and background task by providing a task file.
1✔
5
 * This module allows you to easily schedule tasks using cron expressions with support for timezones and
1✔
6
 * various execution options.
1✔
7
 * 
1✔
8
 * @module node-cron
1✔
9
 */
1✔
10

1✔
11
import { InlineScheduledTask } from "./tasks/inline-scheduled-task";
1✔
12
import { ScheduledTask, TaskFn, TaskOptions } from "./tasks/scheduled-task";
1✔
13
import { TaskRegistry } from "./task-registry";
1✔
14

1✔
15
import validation from "./pattern/validation/pattern-validation";
1✔
16
import BackgroundScheduledTask from "./tasks/background-scheduled-task/background-scheduled-task";
1✔
UNCOV
17

×
UNCOV
18
import path from "path";
×
19
import { pathToFileURL } from "url";
1✔
20

1✔
21
/**
1✔
22
 * The central registry that maintains all scheduled tasks.
1✔
23
 * @private
1✔
24
 */
1✔
25
const registry = new TaskRegistry();
1✔
26

1✔
27

1✔
28
/**
1✔
29
 * Schedules a task to be executed according to the provided cron expression.
1✔
30
 * 
1✔
31
 * @param expression - A cron expression (e.g. '* * * * *' for every minute) that determines when the task executes
1✔
32
 * @param func - Either a function to be executed or a file path to a module containing the task function
1✔
33
 * @param options - Optional configuration for the task including timezone and whether to start immediately
1✔
34
 * @returns The created task instance that can be used to control the task
1✔
35
 * 
1✔
36
 * @example
1✔
37
 * // Schedule an inline function to run every minute
1✔
38
 * const task = schedule('* * * * *', () => console.log('Running every minute'));
1✔
39
 * 
1✔
40
 * @example
1✔
41
 * // Schedule background task by providing a separate file to run daily with a specific timezone
1✔
42
 * const dailyTask = schedule('0 0 * * *', './tasks/daily-backup.js', { timezone: 'America/New_York' });
1✔
43
 */
1✔
44
export function schedule(expression:string, func: TaskFn | string, options?: TaskOptions): ScheduledTask {
1!
UNCOV
45
    const task = createTask(expression, func, options);
✔
UNCOV
46
    task.start();
×
UNCOV
47
    return task;
×
UNCOV
48
}
×
UNCOV
49

×
UNCOV
50
/**
×
UNCOV
51
 * Creates a task instance based on the provided parameters adding it to the registry.
×
UNCOV
52
 * 
×
UNCOV
53
 * @param expression - A cron expression that determines when the task executes
×
UNCOV
54
 * @param func - Either a function to be executed or a file path to a module containing the task function
×
UNCOV
55
 * @param options - Optional configuration for the task
×
UNCOV
56
 * @returns A task instance of the appropriate type (inline or background)
×
UNCOV
57
 * @private
×
UNCOV
58
 */
×
59
export function createTask(expression: string, func: TaskFn | string, options?: TaskOptions): ScheduledTask {
2!
60
    let task: ScheduledTask;
13✔
61
    if(func instanceof Function){
13✔
62
      task = new InlineScheduledTask(expression, func, options);
11✔
63
    } else {
13✔
64
      const taskPath = solvePath(func);
2✔
65
      task = new BackgroundScheduledTask(expression, taskPath, options);
2✔
66
    }
1✔
67

1✔
68
    registry.add(task);
1✔
69
    return task;
1✔
70
}
1✔
71

1✔
72
/**
1✔
73
 * Resolves a relative file path to a file URL path based on the caller's location.
1✔
74
 * 
1✔
75
 * @param filePath - The path to the task file, can be absolute or relative
1✔
76
 * @returns The file URL to the task file
1✔
77
 * @throws Error if the task file location cannot be determined
1✔
78
 * @private
1✔
79
 */
1✔
80
export function solvePath(filePath: string): string {
1✔
81
  // Convert to file URL
5✔
82
  if(path.isAbsolute(filePath)) return pathToFileURL(filePath).href;
5!
83

5✔
84
  // Return immediately if it's a file URL
5✔
85
  if (filePath.startsWith('file://')) return filePath;
5✔
86

1✔
87
  const stackLines = new Error().stack?.split('\n');
5✔
88
  if(stackLines){
5✔
89
    stackLines?.shift();
3✔
90
    const callerLine = stackLines?.find((line) => { return line.indexOf(import.meta.filename) === -1; });
3✔
91
    const match = callerLine?.match(/(file:\/\/)?(((\/?)(\w:))?([/\\].+)):\d+:\d+/);
3✔
92
   
3✔
93
    if (match) {
3✔
94
      const dir = `${match[5] ?? ""}${path.dirname(match[6])}`;
3✔
95
      return pathToFileURL(path.resolve(dir, filePath)).href;
3✔
96
    }
3✔
97
  }
3✔
98

5✔
99
  throw new Error(`Could not locate task file ${filePath}`);
5!
100
}
5✔
101

1✔
102
/**
1✔
103
 * Validates a cron expression to ensure it follows the correct format.
1✔
104
 * 
1✔
105
 * @param expression - The cron expression to validate
1✔
106
 * @returns `true` if the expression is valid, `false` otherwise
1✔
107
 */
1✔
108
export function validate(expression: string): boolean {
1✔
109
  try {
2✔
110
      validation(expression);
2✔
111

2✔
112
      return true;
2✔
113
  // eslint-disable-next-line
2✔
114
  } catch (e) {
2✔
115
      return false;
1✔
116
  }
1✔
117
}
2✔
118

1✔
119
/**
1✔
120
 * Retrieves all scheduled tasks from the registry.
1✔
121
 * 
1✔
122
 * @returns A map of scheduled tasks
1✔
123
 */
1✔
124
export const getTasks = registry.all;
1✔
125

1✔
126
/**
1✔
127
 * Retrieves a specific scheduled task from the registry.
1✔
128
 * 
1✔
129
 * @params taskId - The ID of the task to retrieve
1✔
130
 * @returns The task instance if found, `undefined` otherwise
1✔
131
 */
1✔
132
export const getTask = registry.get;
1✔
133

1✔
134
export type { ScheduledTask } from './tasks/scheduled-task';
1✔
135
export type { TaskFn, TaskContext, TaskOptions } from './tasks/scheduled-task';
1✔
136

1✔
137
export interface NodeCron {
1✔
138
  schedule: typeof schedule;
1✔
139
  createTask: typeof createTask;
1✔
140
  validate: typeof validate;
1✔
141
  getTasks: typeof getTasks;
1✔
142
  getTask: typeof getTask;
1✔
143
}
1✔
144

1✔
145
export const nodeCron: NodeCron = {
1✔
146
  schedule,
1✔
147
  createTask,
1✔
148
  validate,
1✔
149
  getTasks,
1✔
150
  getTask,
1✔
151
};
1✔
152

1✔
153
/**
1✔
154
 * Default export containing the main functions of the module.
1✔
155
 */
1✔
156
export default nodeCron;
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc