staltz / react-native-node

Run a separate Node.js process behind a React Native app
MIT License
1.12k stars 33 forks source link

Running timers on server #11

Closed HZSamir closed 6 years ago

HZSamir commented 6 years ago

Hello again, I am trying to run a timer on the server that executes a certain function every x seconds. Something like:

setTimeout(function() {
  // work
}, delay);

and notifies the main thread each time. However, seeing as the server in your example relies on Express, each request receives an answer once, and I have to fetch the URL again to execute it, and I'm kinda reluctant here as every bit of performance is crucial in this particular project.

What I'm aiming at really is something along the lines of a Worker, something like:

worker.onmessage = message => {
  switch(message) {
    case 'periodicAction':
    // Execute a function, return the result
    worker.postMessage('My result')
    default
    worker.postMessage('Do nothing...')
  }
};

What I'm getting at really is: Is there a way to get rid of Express and replace the node thread with a fullblown worker? And if not, is there some way to have it perform some kind of task periodically and notify the main thread when it's done each time? Something like:

RNNode.sendMessage('a message')

I apologize for creating an issue, as this is not really one Again, thank you

staltz commented 6 years ago

I think WebSockets would really help here, they give you that two-way communication channel that you want. Just use the package ws for node.js on the background process. On the React Native side, there is also WebSocket support, however it has been buggy lately but depending on the version of React Native you use, it may work.

soyuka commented 6 years ago

WDYT about implementing a kind of IPC channel (like electron has) embedded in this library? It could use a TCP client in Java that interfaces sendMessage/onMessage methods available in react. On the backend something like:

const ipc = require('react-native-node').ipc
ipc.onMessage()
ipc.sendMessage()

This could wrap the origin nodejs process to avoid the boilerplate, and onMessage/sendMessage could be exposed globally.

If you're willing to accept such a feature please let me know and I'll definitely work on it!

staltz commented 6 years ago

Soyuka, note that react-native-node spawns a new process, not a new thread. So Java doesn't have any special privilege that JS wouldn't have, that's why I recommend using just JS directly with TCP or Websockets.

If you want to spawn a new JS thread, take a look at react-native-workers which has the API you suggested.

soyuka commented 6 years ago

Mhh, yes I got that. Though I don't see why we couldn't have a TCP client in Java that connects to a node tcp server. This would give the ability to run sendMessage() from the react-native javascript and ease the communication process :).

I'll try a prototype!