From 0044d265d1f7789afd2b432a9cdd47585669f6d7 Mon Sep 17 00:00:00 2001 From: soulteary Date: Tue, 4 Jan 2022 14:18:54 +0800 Subject: [PATCH] chore: bg-task optimization --- server.js | 1 + utils/jobs.js | 49 +++++++++++++++++++++++++++---------------------- 2 files changed, 28 insertions(+), 22 deletions(-) diff --git a/server.js b/server.js index c6f25f9..4170563 100644 --- a/server.js +++ b/server.js @@ -23,6 +23,7 @@ const logger = new Logger(); await initApp(); await connectDB(); await associateModels(); + await jobs(); // Create server for Express API and WebSockets const server = http.createServer(); diff --git a/utils/jobs.js b/utils/jobs.js index 0ce3284..615c5ef 100644 --- a/utils/jobs.js +++ b/utils/jobs.js @@ -6,30 +6,35 @@ const Logger = require('./Logger'); const loadConfig = require('./loadConfig'); const logger = new Logger(); -// Update weather data every 15 minutes -const weatherJob = schedule.scheduleJob( - 'updateWeather', - '0 */15 * * * *', - async () => { - const { WEATHER_API_KEY: secret } = await loadConfig(); +module.exports = async function () { + const { WEATHER_API_KEY } = await loadConfig(); + const FEAT_WHEATHER_ENABLED = WEATHER_API_KEY != ''; - try { - const weatherData = await getExternalWeather(); + if (FEAT_WHEATHER_ENABLED) { + // Update weather data every 15 minutes + const weatherJob = schedule.scheduleJob( + 'updateWeather', + '0 */15 * * * *', + async () => { + try { + const weatherData = await getExternalWeather(); - Sockets.getSocket('weather').socket.send(JSON.stringify(weatherData)); - } catch (err) { - if (secret) { - logger.log(err.message, 'ERROR'); + Sockets.getSocket('weather').socket.send(JSON.stringify(weatherData)); + } catch (err) { + if (WEATHER_API_KEY) { + logger.log(err.message, 'ERROR'); + } + } } - } - } -); + ); -// Clear old weather data every 4 hours -const weatherCleanerJob = schedule.scheduleJob( - 'clearWeather', - '0 5 */4 * * *', - async () => { - clearWeatherData(); + // Clear old weather data every 4 hours + const weatherCleanerJob = schedule.scheduleJob( + 'clearWeather', + '0 5 */4 * * *', + async () => { + clearWeatherData(); + } + ); } -); +};