每天在react.js服务器中运行一次函数


import express from "express"
import cors from "cors"
import bodyParser from "body-parser"
import { MongoClient, ObjectId} from "MongoDB"
const PORT = process.env.PORT|| 3001;
const app=express()
app.use(cors())
app.use(bodyParser.urlencoded({extended:true}))
app.listen(PORT,()=>{
console.log("run");
})
//function that doesn't work
const setUnsetPercentbuysell=()=>{
if(new Date().getHours()===23 && new Date().getMinutes()===59){
MongoClient.connect("mongodb+srv://<user>:<password>@cluster0.pdunp.mongodb.net/<database>?retryWrites=true&w=majority", function(err, db) {
if (err) throw err;
var dbo = db.db("player");
dbo.collection("calcio").updateMany({},{$set:{percentbuysell:{buy:0,sell:0}}},(err,result)=>{
if (err) throw err;
})
})
}
setTimeout(setUnsetPercentbuysell,60000)
}
setUnsetPercentbuysell()

setUnsetPercentbuysell的功能是每分钟运行一次,只在23:59做一些事情。所以我把这个代码保存在我的heroku应用程序中,但不起作用(我写道,MongoClient不是问题所在,也是为了我的隐私(。有人能帮我吗?

我试过写那个代码,但不起作用

您可以使用节点的cron包来实现这一点。

用法如下:

import {CronJob} from 'cron';
const run = () => {
MongoClient.connect("mongodb+srv://<user>:<password>@cluster0.pdunp.mongodb.net/<database>?retryWrites=true&w=majority", function(err, db) {
if (err) throw err;
dbo.collection("calcio").updateMany({},{$set:{percentbuysell:{buy:0,sell:0}}},(err,result)=>{
if (err) throw err;
})
})
}
const job = new CronJob('59 59 23 * * *', run);
job.start()

这将在每天23:59和59秒运行作业。

请务必查看cron以了解有关其工作原理的更多信息。

最新更新