Schedule function and leave the page nodejs

14 views
Skip to first unread message

Aaron Aben Danan

unread,
Jun 15, 2017, 9:43:09 PM6/15/17
to nodejs
Hi :)

I'm building a node.js app and I need to schedule a function and let the user surf on my website. Is it possible ?

If i wasn't that clear, here is an example :
Let's say a user comes on my index page. From this index page I have to schedule a function for tomorrow morning. The user continues his trip on my website and leaves. The function is still scheduled....

Well ! Thank you in advence :)

Zlatko

unread,
Jun 16, 2017, 8:40:16 AM6/16/17
to nodejs
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({
    userId: req.user.id,
    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 CronJob = require('cron').CronJob; // https://www.npmjs.com/package/cron or something similar
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.

Reply all
Reply to author
Forward
0 new messages