DEV Community

Cover image for Script-Scheduler: A cron based NodeJS script runner
Brian Morrison II
Brian Morrison II

Posted on • Originally published at brianmorrison.me

Script-Scheduler: A cron based NodeJS script runner

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)
Enter fullscreen mode Exit fullscreen mode

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());
    }
}
Enter fullscreen mode Exit fullscreen mode

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;

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay