Skip to content

Instantly share code, notes, and snippets.

@daper
Last active February 9, 2017 11:31
Show Gist options
  • Save daper/fac1f46bb2682a48943aab2ed44ca508 to your computer and use it in GitHub Desktop.
Save daper/fac1f46bb2682a48943aab2ed44ca508 to your computer and use it in GitHub Desktop.
POC: Generic timeout to inline-processed tasks with actionhero.js initializer.
'use strict'
exports.task = {
name: 'sendEmail',
description: 'My Task',
frequency: 0,
queue: 'mail',
middleware: [],
run: function (api, params, next) {
(new Promise((res, rej) => {
for(let i = 1; i <= 1e9; i++) {
if(i%1e8 === 0) api.log(String(i/1e8))
}
res();
}))
.then(next, next)
.catch(next)
}
};
'use strict'
const
vm = require('vm'),
util = require('util');
module.exports = {
loadPriority: 1000,
startPriority: 1000,
stopPriority: 1000,
initialize: function (api, next) {
var
timeout = 20*1000, // 3 secs
tmpl = `(%s)(api, params, next)`;
Object.keys(api.tasks.tasks).forEach((name) => {
if(typeof api.tasks.tasks[name]._run === 'undefined') {
api.tasks.tasks[name]._run = api.tasks.tasks[name].run
}
api.tasks.tasks[name].run = (api, params, next) => {
var
result,
contx = vm.createContext(Object.assign({
api: api,
params: params,
next: (err) => {
result = err
}
}, global)),
startTime = new Date().getTime();
try {
vm.runInContext(util.format(tmpl, api.tasks.tasks[name]._run.toString()), contx, { timeout: timeout })
setTimeout(() => { // Append call to end of loop, let fake next exec first and update result var.
next.call(this, result)
});
} catch(e) {
next(e)
}
}
})
next()
},
start: function (api, next) {
api.tasks.enqueue("sendEmail", {to: 'evan@evantahler.com'}, 'mail', function(error, toRun){
api.log('Example task queued');
});
next()
},
stop: function (api, next) {
next()
}
}
const
vm = require('vm'),
util = require('util');
function main(api, params, next) {
var theend;
var func = function awesomeTask() {
var foo = ':)'
console.log('Let us make your stuff...');
// Let's heat it a bit...
for(let i = 1; i <= 1e9; i++) {
if(i%1e8 === 0) console.log(i/1e8)
}
console.log('Hi! This is %s', foo);
next(new Error('uops!'));
},
contx = vm.createContext(Object.assign({
api: api,
params: params,
next: (err) => { theend = err },
}, global)),
tmpl = `
// Template
(%s)(api, params, next)
`;
try {
vm.runInContext(util.format(tmpl, func.toString()), contx, { timeout: timeout*1000 });
next.call(this, theend);
} catch(e) {
next(e);
}
}
var timeout = 3;
main({api: 'foo'}, {params: 'bar'}, (err) => {
console.log('Call outside job. Result => %s', err);
});
console.log('EOF');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment