Zain Samin
Zain Samin

Reputation: 79

How to write cronjobs in seperate file nodejs

I want to write a cron job on node.js which runs every minute. The tutorials that I viewed online all showed the cron job being written in the "App.js" or "server.js" file which is the main file on nodejs.

I want to seperate this into another file for better readability but I cannot find any solution or example online. please help.

I want to write this in a separate file just like we write our routes.

const cron = require("node-cron");

cron.schedule("* * * * *", function() {
    console.log("running a task every minute");
});

Upvotes: 2

Views: 4506

Answers (3)

ckingchris
ckingchris

Reputation: 609

You can create and export javascript modules elsewhere in your express/node.js app like this:

app.js

const express = require('express');

const app = express();
const port = 5000;

require('./tasks/tasks')();

app.listen(port, () => {
    console.log(`App listening at http://localhost:${port}`)
});

tasks.js

const cron = require('node-cron');

module.exports = () => {  
    cron.schedule('* * * * *', () => {
        console.log('running a task every minute');
    });
}

Terminal:

[nodemon] starting `node start app.js`
App listening at http://localhost:5000
running a task every minute

File Structure:

/tasks
    tasks.js
app.js

Upvotes: 6

O. Jones
O. Jones

Reputation: 108851

node-cron emulates, rather than uses, the UNIX / Linux / FreeBSD cron subsystem driven by crontab file entries. node-cron projects the illusion that functions in a running nodejs instance can be scheduled as if they were executable programs.

If you want to schedule a different nodejs program as a cron job, don't use node-cron, use cron. Put an entry in the OS's crontab mentioning the nodejs program.

Upvotes: 0

krbalaji
krbalaji

Reputation: 474

yes. you can write your cron-job in separte file. when starting the server, you can invoke your cron job, like in your app.js or server.js. you just export your cron job file & impore here

import cronJob from "../filename.js"        
server.listen(3000, () => {
   cronJob.start();
});

Upvotes: 4

Related Questions