kelektiv / node-cron

Cron for NodeJS.
MIT License
8.3k stars 617 forks source link

How can i stop the previous job? #868

Closed nsnhan127 closed 1 month ago

nsnhan127 commented 3 months ago

This is my code

import { NextResponse } from "next/server";
import { CronJob, CronTime } from "cron";
let job = CronJob.from({
  cronTime: "* * * * * *",
  onTick: () => {},
  timeZone: "UTC+7",
});
export async function POST(request) {
  const requestData = await request.json();
  const { trigger, value, groupFlows, checkPublished, wId, lNodes, lEdges } =
    requestData.body;
  if (checkPublished) {
      job.addCallback(() => {
        const d = new Date();
        console.log(`Every ${value} ${trigger}:`, d);
      });
      job.start();
      return NextResponse.json({
        success: true,
      });
    } else {
      job.stop();
      return NextResponse.json({
        success: true,
      });
    }
}

When i call in the first time. The result is

Every 1 minutes: 2024-03-15T03:31:38.002Z
Every 1 minutes: 2024-03-15T03:31:39.003Z
Every 1 minutes: 2024-03-15T03:31:40.016Z
Every 1 minutes: 2024-03-15T03:31:41.009Z
Every 1 minutes: 2024-03-15T03:31:42.012Z

But when i stop and call again. The result is

Every 1 minutes: 2024-03-15T03:31:50.016Z
Every 1 minutes: 2024-03-15T03:31:51.008Z
Every 1 minutes: 2024-03-15T03:31:51.009Z
Every 1 minutes: 2024-03-15T03:31:52.015Z
Every 1 minutes: 2024-03-15T03:31:52.015Z

It's seem have another job run in the same time. How can i fix it ?

sheerlox commented 2 months ago

Hey, sorry for the delay!

Your code behaves as expected because you're not resetting the job and simply adding a new callback, the previous callbacks are still present and will all be called upon job execution.

This means there is only one job running but with multiple callbacks. If you'd like to reset it, you would have to recreate it altogether, and probably make sure it was stopped before doing so (to avoid having multiple jobs running at once):

export async function POST(request) {
  const requestData = await request.json();
  const { trigger, value, groupFlows, checkPublished, wId, lNodes, lEdges } =
    requestData.body;

  if (checkPublished) {
      // make sure the previous job is stopped before overriding it
      job.stop();

      // re-create a new job in place of the previous one
      job = CronJob.from({
        cronTime: "* * * * * *",
        onTick: () => {
          const d = new Date();
          console.log(`Every ${value} ${trigger}:`, d);
        },
        timeZone: "UTC+7",
        start: true
      });

      return NextResponse.json({
        success: true,
      });
    } else {
      job.stop();

      return NextResponse.json({
        success: true,
      });
    }
}

Linking to our previous discussion for later reference: https://github.com/kelektiv/node-cron/discussions/864