This article was originally posted to my personal blog on 02/03/2020.
One of the things that I do on a fairly regular basis is try to find ways to automate various processes in my life. To do this, I’ve used a combination of PowerShell scripts running on my server, Microsoft Flow (now called Power Automate), and IFTTT. Well Microsoft has started increasing Flow prices (and they made the HTTP connector Premium), and deploying PowerShell scripts sometimes can be a pain to do since I’m using the Windows Task Scheduler to manage them. I was looking for an easier way to port some of this functionality to something I can run in a Docker container and deploy using standard CI/CD tools.
My solution is what I’ve come to name script-scheduler. It’s a way to have small NodeJS scripts to run a set interval using cron expressions. What the framework does is recursively pull in a directory of specially formatted scripts and schedules them to run based on their cron expression. Here is a sample of what I am currently using in one of my projects;
// Import the package.
const scheduler = require('@brianmmdev/script-scheduler')
// This is the directory where all my scripts live.
const baseDir = `${__dirname}/scripts/`
// Pass it into the scheduler.
scheduler.run(baseDir)
A basic script is composed of three main components;
- A cron expression.
- A function.
- An optional enabled flag. Here is an example of a script that could be run;
module.exports = {
enabled: true,
schedule: \"*/1 * * * *\",
fn: function () {
var date = new Date();
console.log('This script will run every minute!', date.toLocaleString());
}
}
There is plenty more polish that can be added to this thing, but it is in a working state so I figure why not publish it for others to use. Check it out at the links below;
- Github Repo: https://github.com/bmorrisondev/script-scheduler
- NPM Package: https://www.npmjs.com/package/@brianmmdev/script-scheduler Feel free to comment (or better yet, contribute) as you see fit. Happy coding!
Top comments (0)