Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Node.js to send an email every 10 seconds?

I'm not sure what's the best way to add a delay of 10 seconds.

setTimeouts don't work, I'm not sure...

In python, I'm used to doing "time.sleep"

I'm not asking for how to send an email. I'm asking how to execute a command every 10 seconds.

like image 718
TIMEX Avatar asked Jun 07 '13 07:06

TIMEX


People also ask

How do I schedule an email in node js?

Project setup json file which makes it possible to track application dependencies. Now, let's build the server and schedule a cron job. We begin writing codes by importing the express and node-cron modules in the index. js file; then, we create a new Express instance on which we'd build the server.

Can you use setTimeout in node?

The setTimeout function is used to call a function after the specified number of milliseconds. The delay of the called function begins after the remaining statements in the script have finished executing. The setTimeout function is found in the Timers module of Node. js.

Can you send emails with node js?

Whether you're building the next Gmail, cutting-edge email marketing software, or just want to program notifications into your Node. js app, it's easy to send emails using readily-made tools and services. Node. js is one of the most popular (if not the most popular) server-side runtime environment for web applications.

How does setTimeout work in node js?

The setTimeout() executes the function passed in the first argument after the time specified in the second argument. The setTimeout function doesn't block other code and the rest of the code is executed and after a specified time the code inside setTimeout function is executed.


1 Answers

setTimeout will work but you have to recreate the timeout at the end of each function call.

You'd do that like this.

function sendEmail() {
  email.send(to, headers, body);
  setTimeout(sendEmail, 10*1000);
}
setTimeout(sendEmail, 10*1000);

What you probably want is setInterval.

function sendEmail() {
   email.send(to, headers, body);
}
setInterval(sendEmail, 10*1000);
like image 127
Daniel Avatar answered Nov 08 '22 06:11

Daniel