If I understand this correctly, you want the user to be able to trigger this scheduled function? Sure, it can be done, in many ways.
Super simple approach would be something like this:
1. create an endpoint which takes the necessary parameters and stores them into a database
2. create a separate module which:
- runs periodically (e.g. every "tomorrow morning"),
- checks for any scheduled tasks,
- executes and marks them complete.
So if and when the user comes back, you can even show them the status (if you're tracking this by user).
Example:
// Express route for setting schedules.
const route = require('express').Router(); // express route you can mount wherever you need
const db = require('./my-db-setup'); // whatever you use here for the database.
route.post('/scheduled-jobs', function (req, res, next) { const job = new db.Job({
params: req.body.params,
ts: new Date(),
completed: false,
});
job.save() // or however you save stuff to db.
.then(() => res.json({ message: 'Scheduled.' }))
.catch(next);
});
module.exports = route; // now import this in your main express router and mount it to /api or something.
// Than the executive module
const db = require('my-db-setup');
const mySpecialFunction = require('./my-function'); // the actual code that you need to run.
// schedule the job for 8 am every morning
new CronJob('0 0 8 * * *', function() {
// find all jobs scheduled before midnight that are not yet completed.
// this will probably wary based on your db/orm of choice.
const midnight = new Date();
date.setHours(0, 0, 0, 0);
db.find({
ts: {
$lt: midnight
},
completed: false,
})
.then((jobs) => {
// simple forEach, but it might schedule a lot of "parallel" jobs - if there are many jobs, you'll
// probably block the server, so you might wanna get them one by one, or stream them from database,
// especially if you're running more than one instance of the Node process.
jobs.forEach((job) => {
mySpecialFunction(job.userId, job.params)
.then((result) => {
// if you have a callback, mark the job complete or save results or something
job.completed = true;
job.result = result;
job.save();
});
});
})
});
That's one relatively simple way to do your thing, there are a few things to watch for or adjust to your needs, but I guess you can start from here. You can use many databases here, even keep stuff in-memory (with some significant restrains, I recommend against it), and different approaches, but you didn't share many details on your task. Ask (more) specific questions if you get stuck.