node.jstypescriptexpressnode-schedule

node-schedule not working with express app


I'm trying to add a scheduler to my express typescript app and my code is as follows:

app.ts (The port and host are defined)

import express from "express";
import { createServer } from "http";
import { testTask } from "./task/updatePairsTask";

import router from "./api/router";

const app = express();

app.use(express.json());
app.use("/", router);

const httpServer = createServer(app).listen(PORT, HOST, () => {
  console.log(`Started server at ${HOST}:${PORT}`);
});

And I have my job defined here: in updatePairsTask.ts

import schedule from "node-schedule";

export const testTask = schedule.scheduleJob("/1 * * * * *", () => {
  console.log("Words");
});

I assume this should make the scheduler print every one second to the console, but nothing seems to printing once the app starts beyond the "Started server" message.

Could you help with the same?

Thanks.


Solution

  • You can use this package to manipulate Cron tasks in very easy way.

    You can use this website to get cron schedule expression.

    import express from "express";
    import { createServer } from "http";
    import { testTask } from "./task/updatePairsTask";
    // import CronJob from "cron"; // npm i cron
    const CronJob = require("cron").CronJob
    
    import router from "./api/router";
    
    const app = express();
    
    app.use(express.json());
    app.use("/", router);
    
    const job = new CronJob({
        cronTime: '* * * * * *',
        onTick: function () {
            testTask()
        },
        start: false,
        timeZone: 'Asia/Kolkata'
    })
    
    job.start()
    
    const httpServer = createServer(app).listen(PORT, HOST, () => {
      console.log(`Started server at ${HOST}:${PORT}`);
      // you can also put job.start() here.
    });