Crontab task scheduler for Windows
GNU-crontab is one of my favorite Linux tools. Despite I can get it from a Cygwin or a WSL instance, on Windows I favor a more minimalist approach. Here's how it works.
Let's say for example that I want to regenerate a JSON formatted version of my CSV todo file, daily.
First, I installed node-cron, fs, and csvtojson Node modules:
npm install node-cron fs csvtojson
Then, I created the following script.
#!/usr/bin/env node
// filename: test.js
// node modules
//
var fs = require('fs');
var csv = require('csvtojson');
var cron = require('node-cron');
const tasks =[];
// ┌────────────── second (optional)
// │ ┌──────────── minute
// │ │ ┌────────── hour
// │ │ │ ┌──────── day of month
// │ │ │ │ ┌────── month
// │ │ │ │ │ ┌──── day of week
// │ │ │ │ │ │
// │ │ │ │ │ │
// * * * * * *
cron.schedule('0 0 9 * * *', ()=>{
console.log("test node-cron");
csv().fromFile("todo.csv").then((tasks) => {
fs.writeFile ("todo.json", JSON.stringify(tasks), function(err) {
if (err) throw err;
console.log('Completed');
}
);
});
});
It can be eventually compiled into an executable with nexe, if necessary.
Now I have to register the previous script as a native Windows service. I have used Cygrunsrv a Cygwin tool available also from the MSYS2/MINGW64 shell.
It can be installed with the following command:
pacman -S cygrunsrv
Finally, the script can be registered as a service from a shell with elevated privileges:
cygrunsrv -I "CSVTOJSON" -d "regenerate todo json daily " -c ~/Documents/MyNotes -p test.js -a "--daemon --no-detach"
net start CSVTOJSON
This new service it's visible also from Windows Services Manager.
A note
As far as I know, a service cannot interact with the user's desktop since Windows Vista. However, the Log on tab still maintains (probably for backward compatibility) the checkbox "Allow service to interact with desktop", but is obsolete and has no effect.
Remove the service
To get a list of all services registered with cygrunsrv, type:
cygrunsrv -L
To remove the previous service:
net stop CSVTOJSON
cygrunsrv -R CSVTOJSON
Logs
Output from the running service will be saved in /c/msys64/var/log/CSVTOJSON.log