I\'m developing add-on based application. Every add-on use scheduler. Loaded add-on schedule task. My application run only one instance. Sometimes application closed, someti
Thanks for the excellent example Kate, I rue that in my wanderings I didn't come across your code first.
I've had a merry dance with registering scheduled tasks via c# code and unsurprisingly have had to tweak my schedule creation code as I encounter roadblocks on one environment that I hadn't encountered on any previously. I hope I've arrived at the most robust code and thought it might also be of benefit to others if I share some things you might try if encountering environmental issues:
all the best Matt
If you want to interact with the Windows 7 Scheduled Tasks system from your code to create, manage, or delete a task that is no problem. (I cover this in the Windows 7 course I wrote for Pluralsight.) Add a COM reference to TaskScheduler and you then do this sort of thing:
ITaskService scheduler = new TaskSchedulerClass();
scheduler.Connect(null, null, null, null);
ITaskFolder rootFolder = scheduler.GetFolder("\\");
ITaskFolder folder = rootFolder.GetFolders(0).Cast<ITaskFolder>().FirstOrDefault(
f => f.Name == "Windows7Course");
if (folder == null)
{
folder = rootFolder.CreateFolder("Windows7Course", null);
}
ITaskDefinition task = scheduler.NewTask(0);
IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
action.Path = typeof(SayHello.Form1).Assembly.Location;
action.WorkingDirectory = Path.GetDirectoryName(typeof(SayHello.Form1).Assembly.Location);
ISessionStateChangeTrigger trigger = (ISessionStateChangeTrigger)task.Triggers.Create(
_TASK_TRIGGER_TYPE2.TASK_TRIGGER_SESSION_STATE_CHANGE);
trigger.StateChange = _TASK_SESSION_STATE_CHANGE_TYPE.TASK_SESSION_UNLOCK;
task.Settings.DisallowStartIfOnBatteries = true;
task.RegistrationInfo.Author = "Kate Gregory";
task.RegistrationInfo.Description = "Launches a greeting.";
IRegisteredTask ticket = folder.RegisterTaskDefinition(
"GreetReturningUser",
task,
(int)_TASK_CREATION.TASK_CREATE_OR_UPDATE,
null,
null,
_TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
null);
This particular sample runs an exe that is in the same solution (another project). You would have to adjust the Action.Path, Action.WorkingDirectory etc to meet your needs.
Check out this project at CodeProject.
A New Task Scheduler Class Library for .NET