Ben Tidman
Ben Tidman

Reputation: 2139

Azure web role start on deploy

I am working on creating a messaging service that runs in the background of my web role. When the web role starts up it starts a Quartz job that runs once a day and sends some emails. I now have my web role set to never go to sleep because of idle. This allows my job to execute regardless of activity on my site.

The issue that I am having is that if I don't visit my site when its first deployed the job never starts. I am worried that if my webrole ever gets moved to a new instance by some Azure magic that my email service won't be running.

The job is started in Global.asax in the Application_Start method. How do I get my web role to automatically start when it's deployed?

-Edit-

Originally I was trying to start my job from WebRole.cs OnStart, but then I was getting errors from entity framework about my database connection. So if anyone knows how to to access connections strings in my web config from WebRole.cs OnStart that would answer my question too.

Upvotes: 0

Views: 594

Answers (1)

Sandrino Di Mattia
Sandrino Di Mattia

Reputation: 24895

Put your code in your WebRole.cs:

public class WebRole : RoleEntryPoint
{
    public override bool OnStart()
    {
        Task.Factory.StartNew(StartQuartzJob);
        return base.OnStart();
    }

    private void StartQuartzJob()
    {
        // Do work here.            
    }
}

This code runs when your instance starts (after a deploy, after a reboot, ...). The advantage here is that it runs in a different process (WaIISHost.exe) that runs before your web application starts in IIS. So even if you don't have any requests going to that instance or if your application pool recycles, this process will keep running. Keep in mind that, since this is a different process, you won't have access to the web.config

Upvotes: 1

Related Questions