Skip to content

Commit

Permalink
Add features to prevent sleeping, fixes #2
Browse files Browse the repository at this point in the history
  • Loading branch information
ciolt committed Jul 26, 2019
1 parent ae4489f commit 4d32b76
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 8 deletions.
8 changes: 8 additions & 0 deletions functions/refresh-vp.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const SaveVehiclePositions = require('./protobufs/exec-vp')

// Recursively refresh VehiclePositions
const RefreshVP = () => SaveVehiclePositions().then(() => {
setTimeout(RefreshVP, 10000)
})

module.exports = RefreshVP
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@wayline/express",
"private": true,
"version": "1.4.7",
"version": "1.4.8",
"description": "Generates GTFS-RT files for Miami-Dade Transit",
"main": "server.js",
"scripts": {
Expand Down
25 changes: 25 additions & 0 deletions router/keepAlive.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
const fs = require('fs')
const path = require('path')
const RefreshVP = require('../functions/refresh-vp')

const filesrc = dir => path.join(process.cwd(), dir)

const getLastUpdateTime = () => new Promise((resolve, reject) => {
fs.stat(filesrc('./tmp/realtime/VehiclePositions.pb'), (err, stats) => {
if (err) reject(err)
const timestamp = new Date(stats.mtime).valueOf()
resolve(timestamp)
})
})

module.exports = async (req, res, next) => {
const lut = await getLastUpdateTime()

// 20 seconds without an update
// so trigger recursion loop again
if (Date.now() - 20000 > lut) {
RefreshVP()
}

next()
}
11 changes: 4 additions & 7 deletions server.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ require('./functions/tmp-precheck')()
const express = require('express')
const fs = require('fs')
const mainRouter = require('./router/index.js')
const SaveVehiclePositions = require('./functions/protobufs/exec-vp')
const keepAlive = require('./router/keepAlive.js')
const RefreshVP = require('./functions/refresh-vp')
const app = express()

const {
Expand All @@ -25,19 +26,15 @@ const loadGTFSintoFs = async () => {
const CronJob = require('cron').CronJob
const feedUpdater = new CronJob('0 0 */1 * * *', loadGTFSintoFs) // every hour at the 00:00 mark

// Recursively refresh VehiclePositions
const RefreshVP = async () => {
await SaveVehiclePositions()
setTimeout(RefreshVP, 10000)
}

async function start () {
const host = process.env.$HOST || process.env.HOST || '127.0.0.1'
const port = process.env.$PORT || process.env.PORT || 3000

// start cron jobs
feedUpdater.start()

app.use('/realtime', keepAlive)

app.use(express.static('./static', {
dotfiles: 'ignore'
}))
Expand Down

0 comments on commit 4d32b76

Please sign in to comment.