How do I execute an automatic function with node-cron

Viewed 770

I have a function that inserts into the database with the POST method and debugging, I test it with postman, sending it an empty post request, so it executes the controller

The function executes 2 more, than 1 is the one that inserts to the DB, ok, I want to execute this function automatically with node-cron

My functions

export class GettingInfo {

    ReadingFileFromServer = () => {
    
            const file = path.resolve(__dirname, '../../../dist/entity/PRUEBA.txt')
            try {
                const data = fs.readFileSync(file, 'utf-8');
                const lines = data.split("\n")
                let values = []
                let bi = []
                lines.forEach(line => {
                    line.trim()
                    values = line.split("\|", 6).map(a => a.trim());
                    bi.push(values)
                    console.log(bi)
                })
                const convert = this.TransformingFiletoJson(bi)
                console.log(convert)
                const save = this.SavingReferences(convert)
                console.log(save)
            } catch (err) {
                console.error(err), 'something has happened to the file';
            }
        }

for the moment to test it I call it in a controller.ts

    @Post('data')
    createData(){
        const tasks = new GettingInfo(this.referenceService)
        tasks.ReadingFileFromServer()
        return "created! 201 test.."
    }

}

But now, that I want to run it alone, create a file "execute.ts" with the following code and it does not run alone

import cron = require("node-cron")
import {GettingInfo} from "./reference.task";


cron.schedule("5 * * * * *", ()=> {
    const echale = new GettingInfo(this.referenceService)
    echale.ReadingFileFromServer()
    console.log("Executing...")
})
1 Answers

From what I can see in the node-cron documentation you need to start the task in order to start the scheduled cron executions.

Change your code to:

const task = cron.schedule("5 * * * * *", ()=> {
    const echale = new GettingInfo(this.referenceService)
    echale.ReadingFileFromServer()
    console.log("Executing...")
})

task.start()

And it should work.

Related