SamKr
4/25/2017 - 3:08 PM

Create Task

Create Task

// https://www.nuget.org/packages/TaskScheduler/

private void InstallTask()
{
    try
    {
        using (var ts = new TaskService())
        {
            var supported = true;
            var xp = false;

            if (ts.HighestSupportedVersion.Major == 2 && ts.HighestSupportedVersion.Minor < 1) supported = false;
            if (ts.HighestSupportedVersion.Major < 2) xp = true;
            
            var td = ts.NewTask();
            td.RegistrationInfo.Description = "Ondersteunende taak voor HDApp";
            
            td.Triggers.Add(new BootTrigger());

            if (!xp)
            {
                if (supported)
                {
                    td.Settings.DisallowStartOnRemoteAppSession = false;
                }

                td.Principal.RunLevel = TaskRunLevel.Highest;
                td.Settings.AllowDemandStart = true;
                td.Settings.RestartCount = 3;
            }

            td.Settings.StopIfGoingOnBatteries = false;
            td.Settings.DisallowStartIfOnBatteries = false;
            
            td.Settings.Enabled = true;
            td.Settings.ExecutionTimeLimit = new TimeSpan(0);

            td.Actions.Add(new ExecAction(Path.Combine(_installDir, "HDAppSupport.exe"), null, _installDir));

            const string taskName = "HDAppSupport";

            ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
        }
    }
    catch (NotSupportedPriorToException exc)
    {
        AddErrorLog($"InstallTask | NotSupportedPriorToException | {exc}");
    }
    catch (Exception ex)
    {
        AddErrorLog($"InstallTask | {ex}");
    }
}