Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/414.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用节点cron执行自动功能_Javascript_Typescript - Fatal编程技术网

Javascript 如何使用节点cron执行自动功能

Javascript 如何使用节点cron执行自动功能,javascript,typescript,Javascript,Typescript,我有一个使用POST方法插入数据库并进行调试的函数,我使用postman测试它,向它发送一个空POST请求,因此它执行控制器 函数执行2次以上,而不是插入数据库的1次,好的,我想用节点cron自动执行这个函数 我的职能 export class GettingInfo { ReadingFileFromServer = () => { const file = path.resolve(__dirname, '../../../dist/enti

我有一个使用POST方法插入数据库并进行调试的函数,我使用postman测试它,向它发送一个空POST请求,因此它执行控制器

函数执行2次以上,而不是插入数据库的1次,好的,我想用节点cron自动执行这个函数

我的职能

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';
            }
        }
为了测试它,我把它叫做controller.ts

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

}
但是现在,我想单独运行它,用下面的代码创建一个文件“execute.ts”,它不会单独运行

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


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

从我在文档中看到的情况来看,您需要启动任务才能启动定时cron执行

将代码更改为:

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

task.start()
它应该会起作用