Reputation: 221
Is it a good idea to run node async functions in cron jobs?
Yes, NodeJS is single threaded. What will happen when cron invokes function() multiple times?
Say the situations is: - CRON Job runs 5 mins calling function() - The function() may take more than 5 minutes to run - The function() is async
I need to a Backend application in NodeJS that does: - Read data from MongoDB (once) - Based on the data, there might be many Third Party API calls, say GOOGLE API to calculate driving distance between two points - Save the total distance data back to the MongoDB - Update Redis cache
How would you do it?
Your comments are much appreciated!!
Thank you.
Upvotes: 4
Views: 8248
Reputation: 111346
From the point of view of cron it doesn't matter if the functions are synchronous or asynchronous. Cron doesn't run your individual functions - it starts the processes and waits for them to finish. How the process works internally is irrelevant.
Now, what you need to take into account if the process can potentially run for longer than the interval between executions is that it is possible that two processes will run at the same time - unless you explicitly do some locking to prevent that.
If you want your processes to potentially run at the same time (if the new process will not wait for the previous one to finish) then you will have to handle concurrency with possible race conditions. This may not be trivial but you will still have to deal with that even if you used a synchronous, blocking or multithreaded environment so this is not Node-specific or async-specific.
Upvotes: 4