Reputation: 12178
also how can you tell if it is running, enabled/disabled, etc.?
Upvotes: 7
Views: 9502
Reputation: 230
The API can be installed via NuGet. The package name is 'TaskScheduler'. (https://github.com/dahall/taskscheduler)
The following example shows how you can test whether a task is installed using its name and if not install it with an hourly execution.
using (TaskService service = new TaskService())
{
if (!service.RootFolder.AllTasks.Any(t => t.Name == "YourScheduledTaskName"))
{
Console.WriteLine("YourScheduledTaskName is not installed on this system. Do you want to install it now? (y/n)");
var answer = Console.ReadLine();
if (answer == "y")
{
var task = service.NewTask();
task.RegistrationInfo.Description = "YourScheduledTaskDescription";
task.RegistrationInfo.Author = "YourAuthorName";
var hourlyTrigger = new DailyTrigger { StartBoundary = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 1, 0 , 0) };
hourlyTrigger.Repetition.Interval = TimeSpan.FromHours(1);
task.Triggers.Add(hourlyTrigger);
var taskExecutablePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "YourScheduledTaskName.exe");
task.Actions.Add(new ExecAction(taskExecutablePath));
service.RootFolder.RegisterTaskDefinition("YourScheduledTaskName", task);
}
}
}
Upvotes: 5
Reputation: 12178
btw, IRT my accepted solution, here is the CodeProject wrapper code (see http://www.codeproject.com/KB/cs/tsnewlib.aspx ) needed to verify that a scheduledTask exists
I use this in an Integration test so the Assert is NUnit..
public static void VerifyTask(string server, string scheduledTaskToFind)
{
ScheduledTasks st = new ScheduledTasks(server);
string[] taskNames = st.GetTaskNames();
List<string> jobs = new List<string>(taskNames);
Assert.IsTrue(jobs.Contains(scheduledTaskToFind), "unable to find " + scheduledTaskToFind);
st.Dispose();
}
to check if it is enabled, you can do the following:
Task task = st.OpenTask(scheduledTaskToFind);
Assert.IsTrue(task.Status != TaskStatus.Disabled);
Upvotes: 1
Reputation: 27499
There is a Task Scheduler API that you can use to access information about tasks. (It is a com library, but you can call it from C# using pinvokes)
There is an article on codeproject that provides a .net wrapper for the API.
[There is also the schtasks command - more info]
Upvotes: 6