'Use variables instead of numbers to set node-cron schedule

I am very new to node.js. I would like to schedule a cron job based on user inputs and pass these inputs into the cron expression.

I have written a shared wallet in Solidity and would like the owner to be able to schedule transactions to various users (identified by the account address) starting at a specific date and then at the intervals set in the node-cron schedule. I then user Solidity to convert the set date into number of seconds from the current time and set a timeout function based on that.

Currently cron is not identifying Day, Month etc as valid inputs. How should I pass them into cron so that each user can set different intervals.

MSetCron_Map = async(Add, Am, Int) => {
    const {Day, Hour, Minute} = this.state;
    cron_map[Add].push(cron.schedule('Minute Hour Day */${Int} *', () => {
      this.SharedWallet.methods.ReloadAllowance(Add, Am).send({from: this.accounts[0]},function(err, success){
        if(err) return console.log('Reload failed in Solidity');
        if(success) this.SharedWallet.methods.PayOut(Add, Math.round(Am)).send({from: this.accounts[0]});
      });
      console.log('running a task every '+Int+' months');
    }, {
      scheduled: true,
      timezone: "EST"
    }));
    //cron_map[Add].start(); //unecessary since scheduled = true
   }

I tried creating constants and passing them as follows which didn't work:

const {Minute, Hour, Interval} = this.state;
    Int = Interval;
    const M = Minute;
    const H = Hour;
    cron_map[Add].push(cron.schedule('${M} ${H} */${Int} * *', () => {

I would also like to override the previous map variable if there is one. I currently set it up like below and then use cron_map.push() as above passing the entire expression into the cron map (not sure if that's possible). I want the map to store the cron schedule for each user's account address and then replace that if a new schedule is set by the owner. From what I've read a map may not be the best option for this. Any ideas on how to fix these issues would be greatly appreciated.

var cron_map = {};
...
cron_map[recurringAddress] = cron_map[recurringAddress] || [];
...


Solution 1:[1]

cron.schedule('${M} ${H} */${Int} * *', () => {
     //Your Code
})
  • You have used single quotes ('') instead of the backtick (``).
  • Use the below code and you are good to go.
cron.schedule(`${M} ${H} */${Int} * *`, () => {
     //Your Code
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rajan Maurya