我正在開發一個使用每 24 小時更新一次的第三個資料 API 的專案,我有一個代碼,每次我使用 nodeJS 運行它時,我都會將第三個 api 的資料插入到 MONGODB 中,我如何運行一個發送一個如果在第三方 api 上創建了新帳戶,則每 24 小時發出信號并更新 mongoDB 上的資料并添加新帳戶。
這是我目前用來從第三個 API 插入資料的代碼。
const fetch = (...args) =>
import('node-fetch').then(({ default: fetch }) => fetch(...args));
const mongoose = require('mongoose');
mongoose.connect("mongodb://mymongoDBURL/mymongoDBTABLE");
const postSchema = new mongoose.Schema({
id: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
status: {
type: String,
required: false
},
});
const Post = mongoose.model('players', postSchema);
async function getPosts() {
const getPlayers = await fetch("http://localhost:3008/api/players"); <--- THIRD PARTY API RUNNING FROM MY LOCALHOST
const response = await getPlayers.json();
for( let i = 0;i < response.players.length; i ){
const post = new Post({
id: response.players[i]['id'],
name: response.players[i]['name'],
status: response.players[i]['status'],
});
post.save();
}
}
getPosts();```
uj5u.com熱心網友回復:
我建議嘗試在 cronjob 中運行該代碼。例如,您可以使用“Node-Cron”將 cronjob 直接實作到您的代碼中,這是一個在 nodejs 中實作 cron 的包。
如果您想每 24 小時運行一次,您可以使用以下代碼段。
import { schedule } from 'node-cron';
schedule('0 0 * * *', async () => {
//Insert your code which should be executed every 24 hours here
await getPosts();
});
這將在每天午夜運行一次代碼。
您也可以嘗試直接從您的作業系統運行 cronjob,例如在 linux 上使用 crontab。
或者完全不同的方法是使用 setInterval() 函式運行它,它看起來像這樣:
setInterval(async () => {
//Insert your code which should be executed every 24 hours here
await getPosts();
}, 24 * 60 * 60 * 1000);
最大的區別可能是 setInterval 方法會立即啟動,而 cronjob 會等待午夜。除了結果可能幾乎相同。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/527793.html
