I am using the package (websocket) for R to receive messages sent from Discord. For this communication to work, Discord requires for R to send a message every ~40 seconds (what the call the heartbeat).
To do this, I create an infinite while loop like this:
LastTime=Sys.time()
Send=1
while (Send==1){
TimeLapse=as.numeric(Sys.time()-LastTime)
Sys.sleep(1) #added to slow down
if(TimeLapse>=40){
ws$send(JsonKeepAliveMessage)
LastTime=Sys.time()
}
}
This works but the computer gets crazy hot without the Sys.sleep() command. If I put that line the computer run normally, but the problem is that the messages are not received, because the computer is asleep.
While looking this, I found that Python has two alternative ways to have a process wait. time.sleep() blocks, and asyncio.sleep() waits but does not block. Does R has a non-blocking waiting function?
As the promises
library docs state:
async code is hard to write! It is hard in C++, it is hard in Java, it is hard in JavaScript, and sadly, R is no exception.
Having said that, this case may be simpler than most. Generally, async operations are at some point fulfilled. You farm out a long-running operation (e.g. writing a file) to a process which then calls back when it has completed.
However, you wish to send this message every 40 seconds forever, so your promise will never be fulfilled. That makes things simpler. We can use the future
library to run an infinite loop in a background process and regain immediate control of the R terminal.
library(future)
plan(multisession) # so we can run a background process
sendKeepAlive %<-% {
# Note: create your websocket connnection here
# e.g. ws <- WebSocket$new(...); ws$connect() etc.
repeat {
ws$send(JsonKeepAliveMessage)
write(sprintf("Sending at %s", Sys.time()), "./logfile.txt", append = TRUE)
Sys.sleep(40)
}
}
This code will give you control of your R process back immediately. It will write to ./logfile.txt
every 40 seconds to confirm it has sent the message.
Do not try to evaluate sendKeepAlive
. That will block your R terminal, as the background process will never terminate. If left alone, after you run this the sendKeepAlive
process will run forever in the background (or until you close the R session in which you created it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With