One of the most common tasks when creating modules and handlers is to perform some repetitive timed actions, such as mailings, log entries, etc. Let’s create our own module, which will carry this kind of functionality.
For example, let’s define a module that will send an email at a certain time:
public class TimerModule : IHttpModule
{
static Timer timer;
long interval = 30000; //30 seconds
static object synclock = new object();
static bool sent=false;
public void Init(HttpApplication app)
{
timer = new Timer(new TimerCallback(SendEmail), null, 0, interval);
}
private void SendEmail(object obj)
{
lock (synclock)
{
DateTime dd = DateTime.Now;
if (dd.Hour == 1 && dd.Minute == 30 && sent == false)
{
// the settings of the smtp-server from which we will send the email
SmtpClient smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("[email protected]", "password");
// our email with the letter header
MailAddress from = new MailAddress("[email protected]", "Test");
// To whom we're sending
MailAddress to = new MailAddress("[email protected]");
// Create a message object
MailMessage m = new MailMessage(from, to);
// message subject
m.Subject = "Test mail";
// message body
m.Body = "Site Newsletter";
smtp.Send(m);
sent = true;
}
else if (dd.Hour != 1 && dd.Minute !=30)
{
sent = false;
}
}
}
public void Dispose()
{ }
}
This module is configured to send an email at 1:30. The Init() method starts a timer, which calls the SendEmail() method every 30000 milliseconds (30 seconds)
The SendEmail() method uses the lock operator to determine the critical section that can only be accessed by one thread at a time.
To control the sending, we check the current time and the sent variable and, depending on the results, we send a message.
In a similar way we can define other actions, which will be executed at certain intervals.
And after defining the module we register it in web.config:
<system.webServer>
<modules>
<add name="Timer" type="MvcTimerApp.Modules.TimerModule"/>
</modules>
</system.webServer>