In other languages this task is easy, just use something like the following in Python:
while True:
# Program logic that will run forever
time.sleep(5) # Make the program wait for a few seconds
My program will also want to pause execution if there is nothing to process. I don't want it to overload the database with queries.
Background
I am trying to write an application that will act as a background queue processor. It will check the database to see if there are any items in the queue that need to be processed and then this program will write the data to files on the disk. The data will be added to the database intermittently by users of a different system that connects to the same database.
I don't think the forever npm module is a good fit since that module simply checks to see if a script is running and if its not it will restart it and report any standard error or output to a file.
My Thoughts in Code
while(true){
db.dataqueue.find({processed: 0}).count((err, count) => {
if(count == 0){
//Sleep here or don't check the db again for a while
}else{
//Do the processing on the datas and make files. Another database find.count
//call should not happen until the queue is processed.
}
}
I'm not sure how to make it sleep since the callback from mongojs can not affect the while loop. I've looked at doing this with a promise and making the the parent function of this async which might work, but I'm not understanding how to implement it from this answer: How to sleep the thread in node.js without affecting other threads?
Also I have thought about replacing the while(true) with setInterval or setTimeout to make the program persistent. This article has been helpful in understanding the event loop.