Running a Windows Scheduled Task from ASP.net

Chris picture Chris · May 3, 2013 · Viewed 11k times · Source

I have a Windows scheduled task that runs a database import process every hour, but I'd like users to be able to kick it off out-of-schedule by hitting a button in an ASP.net dashboard (running in IIS6 on Windows Server 2003).

The following works perfectly in code-behind ...

var proc = new Process
            {
                StartInfo =
                    {
                        UseShellExecute = false,
                        FileName = @"C:\Windows\System32\schtasks.exe",
                        Arguments = "/run /tn Loader",
                        RedirectStandardError = true,
                        RedirectStandardOutput = true,
                        CreateNoWindow = true
                    }
            };
proc.Start();
proc.WaitForExit();

... but only if the application pool identity is set to Local System (not ideal!). If I leave it as Network Service, the task does not start. So it is presumably a permissions issue.

Is there a way ASP.net can kick off a scheduled task on the server without running the application as Local System? If not, what good alternatives are there?

Update: if nobody on SO knows, I guess it is not possible so I will go with my idea of having my web application write requests to a database table (doubling as an audit log) and creating a second task to poll that table and kick off the main task.

Answer

basher picture basher · Nov 6, 2013

Update your schedule task to trigger off a specific event. Then have your website log that event when the button is clicked - thus starting your scheduled task.

Ex: In my installer I create an event log source for my program, since creating the source requires administrative privileges (you can also use the command line to create the source)

  if (EventLog.SourceExists("MyApp"))
  {
      EventLog.CreateEventSource("MyApp", "Application");
  }

Then in my application, I create an event log entry when the button is clicked.

private void btnOpenOtherApp_Click (object sender, EventArgs e) 
{
    try 
    {
        var log = new EventLog
        {
            Source = "MyApp"
        };
        log.WriteEntry("Start MyOtherApp", EventLogEntryType.Information, 1337);
    } 
    catch (Exception ex) 
    {
        ...   
    }
}

And the task scheduler set to open MyOtherApp when the event is logged. Event viewer