How to add windows scheduler in C#

private void AddDISchedulerInWindowScheduler()
        {
            try
            {
                string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                // Get the service on the local machine
                using (TaskService ts = new TaskService())
                {
                    if (ts.FindTask("apps.exe", true) != null)
                    {
                        if (ts.FindTask("apps.exe", true).IsActive)
                        {
                            Task _task = ts.FindTask("apps.exe", true);
                            TimeSpan _timespan = _task.NextRunTime.Subtract(_task.LastRunTime);
                            if (_timespan.Minutes != _TimeInterval)
                            {
                                ts.RootFolder.DeleteTask("apps.exe");
                            }
                        }
                    }
                    if (ts.FindTask("apps.exe", true) == null)
                    {

                        Version ver = ts.HighestSupportedVersion;
                        bool newVer = (ver >= new Version(1, 2));
                        // Create a new task definition and assign properties
                        TaskDefinition td = ts.NewTask();
                        td.RegistrationInfo.Description = "apps.exe";

                        // Create a trigger that will fire the task at this time every other day
                        //td.Triggers.Add(new DailyTrigger {  DaysInterval = 1 });
                        DailyTrigger dt = (DailyTrigger)td.Triggers.Add(new DailyTrigger { DaysInterval = 1 });
                        dt.Repetition.Duration = TimeSpan.FromDays(1000);
                        dt.Repetition.Interval = TimeSpan.FromSeconds(_TimeInterval * 60);
                        dt.ExecutionTimeLimit = TimeSpan.FromHours(12);

                        // Create an action that will launch Notepad whenever the trigger fires
                        td.Actions.Add(new ExecAction(Application.StartupPath + "/apps.exe", "", null));

                        // Register the task in the root folder
                        ts.RootFolder.RegisterTaskDefinition(@"apps.exe", td);

                        // Remove the task we just created
                        //ts.RootFolder.DeleteTask("Test");
                    }
                }
            }
            catch (Exception ex) {  }
        }



Post a Comment

0 Comments