Nested cron job stop and start issue

1.2k views Asked by At

I want to start two jobs simultaneously, but after some time i will stop one of them and will continue second one. In our case i am starting 2 jobs every 30 seconds and each jobs itself execute every 4 second, If i stop first job in the middle of execution, it will stop and second job is performing its task but the problem is that after 30 second first job also start performing task even though we have stop that job.

Here Is my Code:

var job1;
var job = new CronJob({
    cronTime: '*/30 * * * * *',
    onTick: function () {

        var interval = 4000;
        var index = 0;
        var index1 = 0;
        var users = ['U1', 'U2', 'U3', 'U4']
        var users1 = ['D1', 'D2', 'D3', 'D4']

        job1 = new CronJob({
            cronTime: '*/4 * * * * *',
            onTick: function () {
                  var user = users[index];
                  console.log("Sent To :" + user);
                  index++;
                  if (users.length == index) {
                      job1.stop();
                  }
            },
            start: false,
            timeZone: 'GMT'
        });
        job1.start();

        var job2 = new CronJob({
            cronTime: '*/4 * * * * *',
            onTick: function () {
                var user = users1[index1];
                console.log("Sent To :" + user);
                index1++;
                if (users1.length == index1) {
                    job2.stop();
                }
            },
            start: false,
            timeZone: 'GMT'
        });
        job2.start();
    },
    start: false,
    timeZone: 'GMT'
});
job.start();

For stop job:

job1.stop();
1

There are 1 answers

6
Viddesh On

Your first job starts is just because you have set the cron to run both the jobs at every 30 sec which is what I can see from your code. This will keep on running your whole bunch of stuff to run every 30 sec.