if process argv worker process on message task console log task task t

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
if process.argv[2] == 'worker'
process.on 'message', (task) ->
console.log 'task: ' + task.task
console.log 'args: ' + task.args
try
console.log 'eval func'
func = eval('(' + task.task + ')')
console.log 'eval args'
args = eval('(' + task.args + ')')
console.log 'calling'
#args = (eval('(' + arg + ')') for arg in task.args)
func args... , (result) ->
process.send {status: 'success', result:result}
catch e
console.error 'child process frown exception:',e
process.send {status: 'error', error:e.toString()}
else
fork = require('child_process').fork
class Queue
constructor: () ->
@tasks = []
@worker = fork module.id, ['worker']
@worker.on 'message', @handleWorkerMessage
console.log 'worker created: ' + @worker
handleWorkerMessage: (result) =>
if result.status == 'stopped'
return @stopCallback?()
if @tasks.length == 0
return
if result.status == 'success'
@tasks[0].callback null, result.result
else
@tasks[0].callback result.error, null
@tasks.shift()
@runTask()
push: (task, args..., callback) =>
task = {task: task, args: args, callback: callback}
console.log 'creating task: ' + task
console.log 'args: ' + args
@tasks.push task
if @tasks.length == 1
@runTask()
runTask: () =>
if @tasks.length > 0
a = {task: @tasks[0].task.toString(), args: '[' + [a.toString() for a in @tasks[0].args].toString() + ']' }
console.log 'starting task from queue:', a
@worker.send a
#{task: @tasks[0].task.toString(), args: '[' + [a.toString() for a in @tasks[0].args].toString() +']'}
stop: (callback) =>
@stopCallback = callback
@worker.send 'stop'
module.exports = new Queue()