micro task scheduler
npm install micro-task-schedulermicro-task-scheduler is a lightweight package for scheduling and managing background tasks in Node.js applications using cron syntax. It's useful for handling tasks like sending emails or processing data at specific intervals.
Install the package using npm:
``bash`
npm install microtask-scheduler
Importing the Scheduler
`bash
import { addTask, removeTask, startTask, stopTask, startAll, stopAll } from 'micro-task-scheduler';
`
To add a task, use the addTask function. The function takes three arguments: the task name, the cron time string, and the task function.
`bash
const exampleTask = () => {
console.log('Example task executed.');
};
addTask('exampleTask', ' *', exampleTask);
`
To start a specific task, use the startTask function.
`bash
startTask('exampleTask');
`
To stop a specific task, use the stopTask function.
`bash
stopTask('exampleTask');
`
To remove a specific task, use the removeTask function.
`bash
removeTask('exampleTask');
`
To start all scheduled tasks, use the startAll function.
`bash
startAll();
`
To stop all scheduled tasks, use the stopAll function.
`bash
stopAll();
`
Here's a complete example demonstrating how to use the Micro task Scheduler:
`bash
import { addTask, removeTask, startTask, stopTask, startAll, stopAll } from 'micro-task-scheduler';
function handleTask() {
console.log(Task executed at ${Date.now()});
}
// Add a task
addTask('my-task', '0 0 *', handleTask);
// Start a task
startTask('my-task');
// Stop a task
stopTask('my-task');
// Start all tasks
startAll();
// Stop all tasks
stopAll();
// Remove a task
removeTask('my-task');
``