2 回答

TA貢獻2003條經(jīng)驗 獲得超2個贊
如果希望節(jié)點應(yīng)用程序在特定時間運行特定代碼段,則可以運行一個setTimeout()遞歸“循環(huán)”,該循環(huán)每隔幾毫秒檢查一次時間。如果未經(jīng)過特定時間,則setTimeout()回調(diào)將自行調(diào)用,然后過程將重新開始。但是,如果時間已過去,請執(zhí)行特定的代碼塊并停止遞歸循環(huán)。
const triggerTime = new Date(2019, 05, 05, 02, 30, 0, 0)
function otherCodeToRun() {
// do something...
}
function wait() {
setTimeout(function() {
const currentTime = new Date()
if (currentTime >= triggerTime) {
otherCodeToRun() // not calling wait ends the recursive loop
} else {
wait() // recursively call wait after the timeout completes
}
}, 1000) // wait 1 second
}
從理論上講,該otherCodeToRun()函數(shù)可以調(diào)用另一個節(jié)點進程來運行您的其他文件,或者可以將您的其他文件作為模塊加載并以這種方式運行。
另外值得注意的是,您可以在while循環(huán)內(nèi)執(zhí)行此檢查,但是,應(yīng)用程序?qū)⑼耆枞?,這意味著它將顯得無響應(yīng),并可能占用大量CPU周期。setTimeout方法使您的應(yīng)用程序有機會屈服于其他進程,從而使您可以將輸出記錄到控制臺,例如,如果要顯示倒計時。

TA貢獻1880條經(jīng)驗 獲得超4個贊
它可能看起來應(yīng)該更像這樣(絕對路徑,以防萬一):
20 14 2 5 * cd / path / to / Documents / node_bot && / path / to / node fog1.js
它于5月2日14:20運行
添加回答
舉報