5

Trying to run the tasks based on schedule using node-cron 'https://github.com/merencia/node-cron'.

Task creation and starting it:

var cron = require('node-cron'),
task = cron.schedule('* * * * * *', function () {
    console.log('task running...',JSON.stringify(task));
    }, false);
task.start();

To stop the task:

task.stop();

To destroy the task:

task.destroy();

The code works fine when tasks are executed within the scope of where they are created. But as per the requirement how can i access the 'task' later from a different function. Can the task be stored in the backend to perform 'stop()' or 'destroy()' functions on it later. If not possible with the node-cron what else can be used. Working with node.js and mongoDb.

Arvind
  • 61
  • 1
  • 3

2 Answers2

5

I faced the same Issue. Using node-schedule solved the issue:

start the custom Job:

  const campaignId = "MY_CUSTOM_ID"
  let job = schedule.scheduleJob(campaignId, '* * * * * *', function () {
    console.log('running campaign: ' + campaignId)
  })

stop the custom Job:

  const campaignId = "MY_CUSTOM_ID"
  let current_job = schedule.scheduledJobs[campaignId]
  current_job.cancel()
Alan
  • 9,167
  • 4
  • 52
  • 70
4

No, it is not possible to store objects such as this in a data storage. You will need some other system to manage your tasks.

One such system could be a globally available manager where you register tasks by some id so that anybody who knows this id can get access to the task. The id can then be stored in a database.

Very simple implementation:

TaskManager.js

const tasks = [];

const add = (task) => {
  tasks.push(task);
  return tasks.length;
};

const get = (id) => tasks[id];

module.exports = {
  add,
  get,
};

module1.js

const TaskManager = require('TaskManager.js');

const task = cron.schedule( /* ... */ );
const id = TaskManager.add(task);
DB.store('task_id', id)

module2.js

const TaskManager = require('TaskManager.js');

const id = DB.get('task_id');
const task = TaskManager.get(id);

Another approach could be a TaskManager that listenes for events or periodically checks a value in your database and stops tasks based on that.

Lucas S.
  • 2,303
  • 1
  • 14
  • 20