Skip to content

Instantly share code, notes, and snippets.

@nullivex
Last active August 29, 2015 13:58
Show Gist options
  • Save nullivex/9979588 to your computer and use it in GitHub Desktop.
Save nullivex/9979588 to your computer and use it in GitHub Desktop.
Example JS stat bucket roller
'use strict';
var statTracker = function(interval){
if(!interval) interval = 60000
//hits (would be stored in mongo
var hits = {total: 0, hour: 0, day: 0, month: 0}
//last counters
var last = {hour: 0, day: 0, month: 0}
//previous time increments
var previous = {hour: 0, day: 0, month: 0}
var run = function(){
setTimeout(run,interval)
var now = new Date().now()
if(previous.hour < now.getHours()){
hits.hour = hits.total - last.hour
last.hour = hits.total
previous.hour = now.getHours()
}
if(previous.day < now.getDay()){
hits.day = hits.total - last.day
last.day = hits.total
previous.day = now.getDay()
}
if(previous.month < now.getMonth()){
hits.month = hits.total - last.month
last.month = hits.total
previous.month = now.getMonth()
}
}
}
'use strict';
var Model = {}
var statTracker = function(interval){
if(!interval) interval = 60000
var previous = {}
var run = function(network,last){
//setup our increment trackers since they need to be contextual now
if(!last) last = {}
//call the timeout for the next run with our context and last pointers
setTimeout(function(){run(network,last)},interval)
//do some stat tracker shit in here
var now = new Date().now()
var changed = false
if(previous.hour < now.getHour()){
changed = true
//stuff
}
if(changed) network.save()
}
var stream = Model.find().stream()
stream.on('data',function(network){
//fire off the intial stat collector loop with the proper context
//one per network
run(network)
})
stream.on('end',function(){
console.log('finished setting up run loops')
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment