Today on endpoint.tv I showed how to create a workflow service that can do background work on a scheduled basis (The sample code is posted here).  In the example I showed a web UI that allows you to start the job by clicking on a submit button.

Somebody asked me if there was a way to do this without a human starting the process.  They wanted the system to automatically start the process whenever the app started up.

Yes there is a way and here is how you can do it.  I decided to add some settings to web.config that would allow you to create an auto start counter.

Add the following to web.config

<configuration>

<appSettings>
<!-- The following will cause a batch process to start counting when the app auto-starts. -->
<!-- The format is (count to)|(delay)-->
<add key="AutoCount" value="1000|10"/>
</appSettings>

Add the following code to the Global.asax.cs file in the Application_Start method

private void Application_Start(object sender, EventArgs e)

{
// Code that runs on application startup
string autoCount = ConfigurationManager.AppSettings["AutoCount"];

if (string.IsNullOrWhiteSpace(autoCount)) return;

var values = autoCount.Split('|');

// Check for valid value
if (values.Length != 2)
return;

int count;
if (!Int32.TryParse(values[0], out count)) return;

int delay;
if (!Int32.TryParse(values[1], out delay)) return;

var request = new BatchRequest
{
CountTo = count,
Delay = TimeSpan.FromSeconds(delay),
StartAt = DateTime.Now
};

var proxy = new BatchWorkerClient(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/BatchWeb/BatchWorker.xamlx"));
try
{
var response = proxy.SubmitJob(request);
proxy.Close();
}
catch
{
proxy.Abort();
throw;
}
}

Then using IIS manager do the following

Enable named pipes

  1. Right click on the BatchWeb site and select Manage Application / Advanced Settings
  2. Add net.pipe to the list of enabled protocols

Enable Auto-Start

  1. Right click on the BatchWeb site and select Manage WCF and WF Services
  2. On the Auto-Start tab set the app to auto start

Now when the system boots (or the app pool recycles) the system will start a counting job.  You might want to include a way to check and see if the batch work is already in process before starting another one.  My code always starts up a new one.