1

I want to execute a particular line of code at timed intervals. The line will be res.write(""), to keep a connection alive.

This is similar to hardware interrupts in embedded systems.

Is it possible to have a function that inside will run my code, but at 20 seconds period to execute one particular line of code?

3
  • 2
    You might want to take a look at web sockets. Commented Sep 18, 2018 at 13:01
  • Do they offer this functionality? Commented Sep 18, 2018 at 13:01
  • take a look to setInterval() function Commented Sep 18, 2018 at 13:02

2 Answers 2

4

The code res.write("") not necessary will send something to the wire, since the payload is empty. What you might need is TCP keepalive functionality.

 res.connection.setKeepAlive(true, 20000)
Sign up to request clarification or add additional context in comments.

4 Comments

My code consists of a function that takes a lot of time to finish and Heroku throws an H12 timeout error for more than 30 seconds of not serving a response. I hope this line will trick Heroku. Thanks a lot!
The link you provided, does not contain any res.connection.setKeepAlive() function. It only caontains, socket.setKeepAlive([enable][, initialDelay]). Is this the one you are referring to?
Sure, res.connection is just my guess how one can access the underlying socket object having a reference to a request. You can also try req.connection or look for the information about accessing of the connection in the framework you use.
So you wrote res.connection.setKeepAlive(true, 20000), instead of socket.setKeepAlive(true, 5000);, because i am using the express framework. Is my assumption correct?
2

You can use setInterval

https://developer.mozilla.org/fr/docs/Web/API/WindowTimers/setInterval

setInterval(() => res.write(""), 20000);

3 Comments

While not 'wrong' per se, this really isn't a great way to keep a connection alive.
I absolutely agree to that. I was responding more to the beginning of the question which is I want to execute a code, but at timed intervals
If you decide to go with setInterval, don’t forget to close interval after sending the response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.