Rogier
Rogier

Reputation: 81

Run a method asynchronous on the server

I have a Meteor server method that executes a function that I want to run in the background. I want the server method to continue while the function runs in a different process.

the method:

myMethod: function(arg) { 
   _event.emit("myEvent",args);
   ...do some other stuff
}

I'd like the server to do the other stuff and return to the client, and to do the stuff in _event.emit in the background no results have to be sent back to the client.

What it currently does is run the stuff in _event.emit and than the other stuff and then return to the client.

I tried to solve it by doing a call on server side with an empty callback function, but that didn't do the trick

myMethod: function (arg) {
   return Meteor.call("secondMethod", _.toArray(arg), function() {})
}
secondMethod: function (arg) {
   _event.emit("myEvent",args);
}

hope someone knows a solution for this. thanks

Upvotes: 1

Views: 582

Answers (2)

Michel Floyd
Michel Floyd

Reputation: 20256

On the server you can just use Meteor.setTimeout() to run a function asynchronously. Just use an interval of zero if you want to return control immediately. Your main function will continue to run and as soon as there's nothing left in the event queue the scheduled task will run (or it will wait the amount of time you specify if non-zero).

Upvotes: 1

jfriend00
jfriend00

Reputation: 708036

The javascript in nodejs is single threaded. It works off an event queue where an event is popped off the queue, some callback is called to serve that event and the code behind that callback runs to completion, then the next event is pulled off the event queue and the process is repeated.

As such, there is no real "background processing". If your JS thread is executing, then nothing else can run at that time until that JS thread finishes and allows the next event in the event queue to be processed.

To truly run something else in parallel where both your task and other nodejs code can literally run at the same time, you would have to create a new process and let the new process carry out your task. This new process could be any type of process (some pre-built program running a task or another custom nodejs process).

"Running in the background" can sometimes be simulated by time slicing your "background" process work such that it does small amounts of work on timer ticks and the pauses between timer ticks allow other nodejs JS events to be processed and their code to run. But, to do this type of simulated "background", you have to write your task to execute in small chunks. It's a different (and often more cumbersome) way of writing code.

Upvotes: 3

Related Questions