'What is the proper way to set up this Cron Task after a restart?

I am building an IOT application which connects to an MQTT server where users subscribe to a topic for a particular building. I am able to connect, retrieve the information I need, and save it to a database.

The problem is, each individual user is stored in the session, and the connection parameters are submitted in a form, thereby the Subscribe function, which is needed for the topic subscription loses the information it needs for connection on each server restart.

What is the proper way to setup a cron task, which stores the submitted info for each user, along with their session, when the server is restarted(especially when it crashes from a bug)?

var mqtt = require('mqtt');
var Building = require('../models/Building')
var Volume= require('../models/Volume')
/////////////////////////////////////////////////////////////////////////

var today = new Date();
var date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();

///////////////////////START MQTT SUBSCRIPTION//////////////////////////////////////////////////////////////////
const Subscribe = async (req, res, name) => {

    const options = {
        port: port,
        username: req.body.username,
        password: req.body.password,
        clientId: "someclientid"
    }

    const client = mqtt.connect("someserver", options);
    var topic_list = "sometopic"

    client.on('connect', function () {
        client.subscribe(topic_list, function (err, granted) {
            if (err) {
                console.error(err);
                return;
            }
            console.log('Subscribed to topic: ' + topic_list);
        });
        console.log("connected flag  " + client.connected);
    })

    client.on('message', function (topic, message, packet) {
        var msgObject = JSON.parse(message.toString())
     
        var data = JSON.stringify(msgObject.data).slice(-9, -5);
        console.log(JSON.stringify(msgObject.data))

        var v = new DataView(new ArrayBuffer(4))
        v.setUint32(0, `0x${data}0000`)
        console.log('message is ' + v.getFloat32(0))
        var decimal = v.getFloat32(0);
        storedata(req, decimal, name);
    });
}
/////////////////////////End MQTT SUBSCRIPTION//////////////////////////////////////////////

async function storedata(req, value, name) {

    const absvalue = Math.abs(value)
    if (absvalue != 0) {
        var building = await Building.findOne({
            user: req.user,
            name: name
        });
        if (building) {
            const oldvolume = await Volume.create({source:name, calculated_at:date, volume:absvalue, user:req.user});
            oldvolume.save()
            console.log(oldvolume)
        }
    }
}

module.exports.Subscribe = Subscribe;


Sources

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

Source: Stack Overflow

Solution Source