示例#1
2
 static void Main(string[] args)
 {
     TaskService ts = new TaskService();
     var tasks = ts.FindAllTasks(new Regex(string.Empty));
     var task = ts.GetTask("Elevate");
     TaskDefinition td = ts.NewTask();
     td.Principal.RunLevel = TaskRunLevel.Highest;
     //td.Triggers.AddNew(TaskTriggerType.YourDesiredSchedule);
     td.Triggers.AddNew(TaskTriggerType.Registration);
     //td.Actions.Add(new ExecAction("Path Of your Application File", null));
     td.Actions.Add(new ExecAction(@"E:\StructuresSrc\Kit\bin\gacutil.exe", "/nologo /u \"Tekla.Logging, Version=99.1\""));
     ts.RootFolder.RegisterTaskDefinition("GatUtil", td);
     td.Actions.Add(new ExecAction(@"E:\StructuresSrc\MSBuild\MSBuild\MSBuildTasks\Elevate.exe", "E:\\StructuresSrc\\Kit\\bin\\gacutil.exe /nologo /u \"Tekla.Logging, Version=99.1\""));
     ts.RootFolder.RegisterTaskDefinition("Elevate", td);
     ts.RootFolder.DeleteTask("Elevate", false);
 }
示例#2
1
 public static bool IsAutostart()
 {
     using (TaskService ts = new TaskService())
     {
         Microsoft.Win32.TaskScheduler.Task task = ts.GetTask("Touchmote");
         return task != null;
     }
 }
示例#3
1
 public void DeleteTask(string name)
 {
     using (TaskService ts = new TaskService())
     {
         if (ts.GetTask(name) != null)
         {
             ts.RootFolder.DeleteTask(name);
         }
     }
 }
示例#4
1
 public static void modifyTask(DailyTrigger dt)
 {
     using (TaskService ts = new TaskService())
     {
         Task t = ts.GetTask("taxiService");
        TaskDefinition td = t.Definition;
        td.Triggers.Add(dt);
        ts.RootFolder.RegisterTaskDefinition(@"taxiService", td);
     }
 }
 public static void RunTask()
 {
     using (TaskService ts = new TaskService())
     {
         Task t = ts.GetTask("CudaAdministratorSkipUAC");
         if (t != null)
         {
             t.Run();
         }
     }
 }
        /// <summary>
        /// Ctor
        /// </summary>
        public JobScheduler()
        {
            InitializeComponent();

            LoadJobPlugIns();

            try
            {

                using (TaskService ts = new TaskService())
                {
                    //Load which jobs are already scheduled in the service.
                    foreach (IScheduledJob job in this.ScheduledJobs)
                    {
                        job.JobConfig.LoadConfig();

                        string jobName = job.ToString().Substring(job.ToString().LastIndexOf('.') + 1);
                        string taskName = jobName + "-" + job.JobId.ToString();

                        TaskFolder sysconTaskFolder = GetTaskFolder(ts, SYSCON_TASK_FOLDER);
                        Task t = null;

                        // Retrieve the task
                        if (sysconTaskFolder != null)
                        {
                            //Get from Syscon folder
                            t = sysconTaskFolder.Tasks.FirstOrDefault(tt => tt.Name == taskName);
                        }
                        else
                        {
                            //get from Root folder
                            t = ts.GetTask(taskName);
                        }

                        job.JobConfig.ScheduledTime = (t != null) ? t.Definition.Triggers[0].ToString() : NOT_SET;
                        job.JobStatus = (t != null) ? (JobStatus)t.State : JobStatus.Disabled;
                        job.Enqueued = (t != null);

                        job.JobConfig.SaveConfig();
                    }
                }
            }
            catch (Exception ex)
            {
                Env.Log("Exception in accessing the windows task scheduler information for the plug-ins.\nException: {0}\n StackTrace: {1}", ex.Message, ex.StackTrace);
                if (ex.InnerException != null)
                {
                    Env.Log("InnerException: {0}\n StackTrace: {1}", ex.InnerException.Message, ex.InnerException.StackTrace);
                }
            }
        }
示例#7
1
        public void Delete(IEnumerable<RepetitiveTask> tasks)
        {
            using (var ts = new TaskService())
            {
                foreach (var t in tasks)
                {
                    var task = ts.GetTask(t.Name);
                    if (task != null)
                    {
                        WaitForTaskToComplete(task, t);

                        ts.RootFolder.DeleteTask(t.Name);

                        OnTaskDeletedEvent(new TaskEventArgs { Task = t });
                    }
                }
            }
        }
示例#8
1
        public void Disable(IEnumerable<RepetitiveTask> tasks)
        {
            using (var ts = new TaskService())
            {
                foreach (var t in tasks)
                {
                    var task = ts.GetTask(t.Name);
                    if (task != null)
                    {
                        WaitForTaskToComplete(task, t);

                        task.Enabled = false;
                        task.RegisterChanges();

                        OnTaskDisabledEvent(new TaskEventArgs { Task = t });
                    }
                }
            }
        }
        static void Main(string[] args) {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            for (int x = 0, cx = args.Length; x < cx; x++) {
                if ("/tn".Equals(args[x], StringComparison.InvariantCultureIgnoreCase)) {
                    x++;
                    if (x < cx) {
                        using (TaskService ts = new TaskService()) {
                            var t = ts.GetTask(args[x]);
                            if (t.ShowEditor()) {
                                t.RegisterChanges();
                            }
                        }
                        break;
                    }
                }
            }
        }
        internal static void EditorTest(TaskService ts, System.IO.TextWriter output, params string[] arg)
        {
            try
            {
                const string taskName = "Test";

                // Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();
                /*td.RegistrationInfo.Description = "Test for XP SP3";
                td.RegistrationInfo.Author = "incaunu";*/
                td.Triggers.Add(new DailyTrigger() { StartBoundary = new DateTime(2014, 1, 15, 9, 0, 0), EndBoundary = DateTime.Today.AddMonths(1) });
                /*EventTrigger eTrig = new EventTrigger("Security", "VSSAudit", 25);
                eTrig.ValueQueries.Add("Name", "Value");
                td.Triggers.Add(eTrig);*/
                //td.Actions.Add(new ExecAction("cmd.exe", "/c \"date /t > c:\\cmd.txt\""));
                EmailAction ea = (EmailAction)td.Actions.Add(new EmailAction("Hi", "*****@*****.**", "[email protected]; [email protected]", "<p>How you been?</p>", "smtp.codeplex.com"));
                ea.HeaderFields.Add("reply-to", "*****@*****.**");
                ea.Attachments = new object[] { (string)new TemporaryScopedFile(), (string)new TemporaryScopedFile() };
                //WriteXml(td, taskName);
                Task t = ts.RootFolder.RegisterTaskDefinition(taskName, td); //, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
                System.Converter<DateTime, string> d = delegate(DateTime ints) { return ints == DateTime.MinValue ? "Never" : ints.ToString(); };
                output.Write("***********************\r\nName: {0}\r\nEnabled: {1}\r\nLastRunTime: {2}\r\nState: {3}\r\nIsActive: {4}\r\nNextRunTime: {5}\r\nShouldHaveRun: {6}\r\nTriggerStart: {7}\r\nTriggerEnd: {8}\r\n",
                    t.Name, t.Enabled, d(t.LastRunTime), t.State, t.IsActive, t.NextRunTime, d(t.LastRunTime), t.Definition.Triggers[0].StartBoundary, t.Definition.Triggers[0].EndBoundary);
                WriteXml(t);

                // Register then show task again
                while (DisplayTask(ts.GetTask(taskName), true) != null)
                {
                    Task t2 = editorForm.Task;
                    output.Write("***********************\r\nName: {0}\r\nEnabled: {1}\r\nLastRunTime: {2}\r\nState: {3}\r\nIsActive: {4}\r\nNextRunTime: {5}\r\nShouldHaveRun: {6}\r\nTriggerStart: {7}\r\nTriggerEnd: {8}\r\n",
                        t2.Name, t2.Enabled, t2.LastRunTime, t2.State, t2.IsActive, t2.NextRunTime, t2.LastRunTime, t2.Definition.Triggers[0].StartBoundary, t2.Definition.Triggers[0].EndBoundary);
                }

                // Remove the task we just created
                ts.RootFolder.DeleteTask(taskName);
            }
            catch (Exception ex)
            {
                output.WriteLine(ex.ToString());
            }
        }
示例#11
1
 // Deklaration des Tasks "AutoImage"
 private void schedTask()
 {
     TaskService ts = new TaskService();
     TaskFolder tf = ts.RootFolder;
     string tasks = ts.RootFolder.AllTasks.ToString();
     if (tf.Tasks.Exists("AutoImage") == true)
     {
         Task task = ts.GetTask("AutoImage");
         task.Run();
     }
     else
     {
         MessageBox.Show("Task ist nicht vorhanden", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
示例#12
1
 public Microsoft.Win32.TaskScheduler.Task GetScheduledTask()
 {
     using (TaskService ts = new TaskService())
     {
         Microsoft.Win32.TaskScheduler.Task t = ts.GetTask(m_internalTaskName);
         return t;
     }
 }
示例#13
1
 public void Clean()
 {
     if (m_task == null) return;
     using (TaskService ts = new TaskService())
     {
         Microsoft.Win32.TaskScheduler.Task t = ts.GetTask(m_internalTaskName);
         if (t != null) ts.RootFolder.DeleteTask(m_internalTaskName);
     }
 }
示例#14
1
        private void StartNew(DateTime startTime, string action, string parameters, string taskName)
        {
            using (TaskService ts = new TaskService())
            {
                TaskDefinition td = ts.NewTask();
                td.Principal.RunLevel = TaskRunLevel.Highest;
                td.RegistrationInfo.Description = "instaprinter";

                td.Triggers.Add(new TimeTrigger(startTime));
                td.Actions.Add(new ExecAction(action, parameters));

                // Retrieve the task, change the trigger and re-register it
                Task t = ts.GetTask(taskName);
                if (t != null)
                {
                    td = t.Definition;
                    td.Triggers[0].StartBoundary = startTime;

                    ts.RootFolder.RegisterTaskDefinition(taskName, td);
                }
                else
                {
                    ts.RootFolder.RegisterTaskDefinition(taskName, td);
                }
            }
        }
 /// <summary>
 /// Saves the specified sections of the security descriptor associated with this <see cref="T:System.Security.AccessControl.ObjectSecurity" /> object to permanent storage. We recommend that the values of the <paramref name="includeSections" /> parameters passed to the constructor and persist methods be identical. For more information, see Remarks.
 /// </summary>
 /// <param name="name">The name used to retrieve the persisted information.</param>
 /// <param name="includeSections">One of the <see cref="T:System.Security.AccessControl.AccessControlSections" /> enumeration values that specifies the sections of the security descriptor (access rules, audit rules, owner, primary group) of the securable object to save.</param>
 protected override void Persist(string name, AccessControlSections includeSections = AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner)
 {
     using (var ts = new TaskService())
     {
         var task = ts.GetTask(name);
         Persist(task, includeSections);
     }
 }
示例#16
1
        private void btnScheduleTasks_Click(object sender, EventArgs e)
        {
            using (var taskService = new TaskService())
            {
                if (taskService.GetTask("SP_Field_Monitor") == null)
                {
                    CreateTask(taskService);
                }
                else
                {
                    taskService.RootFolder.DeleteTask("SP_Field_Monitor");

                    if (taskService.GetTask("SP_Field_Monitor_Check") != null)
                            taskService.RootFolder.DeleteTask("SP_Field_Monitor_Check");

                    CreateTask(taskService);
                }
            }
        }
        /// <summary>
        /// Performs the check.
        /// </summary>
        /// <returns>
        ///   <c>true</c> if the check succeeds otherwise, <c>false</c>.
        /// </returns>
        public override bool PerformCheck()
        {
            using (var ts = new TS.TaskService(ServerName, UserName, Domain, Password))
            {
                var task = ts.GetTask(TaskName);

                return task.LastTaskResult == 0;
            }
        }
示例#18
1
 private void task_scheduler_Load(object sender, EventArgs e)
 {
     using (TaskService ts = new TaskService())
     {
         Task t = ts.GetTask("taxiService");
        if(t != null) taskDefined = true;
     }
 }
        private void jobsDataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;

            ScheduledJobModel scheduledJobModel = (ScheduledJobModel)jobsDataGridView.Rows[e.RowIndex].DataBoundItem;

            if (e.ColumnIndex == jobsDataGridView.Columns["Config"].Index && e.RowIndex >= 0)
            {
                scheduledJobModel.Job.SetJobConfiguration();
            }

            if (e.ColumnIndex == jobsDataGridView.Columns["Enqueue"].Index && e.RowIndex >= 0)
            {
                DataGridViewCheckBoxColumn col = jobsDataGridView.Columns["Enqueue"] as DataGridViewCheckBoxColumn;
                DataGridViewCheckBoxCell cell = jobsDataGridView.Rows[e.RowIndex].Cells["Enqueue"] as DataGridViewCheckBoxCell;

                bool enqueued = !((bool)cell.EditingCellFormattedValue);

                //Add the entry to service app.config file.
                string exeLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                //Add to the windows scheduler
                using (TaskService ts = new TaskService())
                {
                    string jobName = scheduledJobModel.Job.ToString().Substring(scheduledJobModel.Job.ToString().LastIndexOf('.') + 1);
                    string taskName = jobName + "-" + scheduledJobModel.Job.JobId.ToString();

                    if (enqueued)
                    {
                        //If enqueued then add to the scheduled task list
                        ScheduledTaskSettingsDialog schedulerTaskSettingsDlg = new ScheduledTaskSettingsDialog();
                        if (schedulerTaskSettingsDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        {
                            // Create a new task definition and assign properties
                            TaskDefinition td = ts.NewTask();
                            td.RegistrationInfo.Description = scheduledJobModel.Job.JobDesc;
                            td.Principal.LogonType = TaskLogonType.InteractiveToken;
                            td.Principal.RunLevel = TaskRunLevel.Highest;
                            td.Settings.DisallowStartIfOnBatteries = false;
                            td.Settings.StopIfGoingOnBatteries = false;

                            // Add a trigger that will fire the task at this time every day
                            DailyTrigger dt = (DailyTrigger)td.Triggers.Add(new DailyTrigger { DaysInterval = 1, StartBoundary = schedulerTaskSettingsDlg.StartBoundary });
                            dt.Repetition.Interval = TimeSpan.FromMinutes(schedulerTaskSettingsDlg.TimeInterval);

                            // Add an action that will launch the job runner application for the given job at the scheduled time.
                            td.Actions.Add(new ExecAction("ScheduledJobRunner.exe", scheduledJobModel.Job.JobId.ToString(), exeLocation));

                            //Try creating the Syscon folder
                            TaskFolder sysconTaskFolder = CreateSysconScheduledTaskFolder(ts);
                            if (sysconTaskFolder != null)
                            {
                                // Register the task in the Syscon folder
                                sysconTaskFolder.RegisterTaskDefinition(taskName, td);
                            }
                            else
                            {
                                // Register the task in the root folder
                                ts.RootFolder.RegisterTaskDefinition(taskName, td);
                            }
                            scheduledJobModel.Enqueued = enqueued;
                            //cell.EditingCellFormattedValue = true;

                            scheduledJobModel.ScheduledTime = td.Triggers[0].ToString();
                            scheduledJobModel.JobStatus = JobStatus.Ready;
                            scheduledJobModel.Job.JobConfig.ScheduledTime = scheduledJobModel.ScheduledTime;
                            scheduledJobModel.Job.JobConfig.SaveConfig();

                            MessageBox.Show("Job successfully added to the Windows scheduled tasks.");
                        }
                        else
                        {
                            scheduledJobModel.Enqueued = false;
                            //cell.EditingCellFormattedValue = false;
                        }
                    }
                    else
                    {
                        Task t = null;

                        TaskFolder sysconTaskFolder = GetTaskFolder(ts, SYSCON_TASK_FOLDER);
                        if (sysconTaskFolder != null)
                        {
                            //Get from Syscon folder
                            t = sysconTaskFolder.Tasks.FirstOrDefault(tt => tt.Name == taskName);

                            //Remove the task from Syscon folder
                            sysconTaskFolder.DeleteTask(taskName, false);
                        }
                        else
                        {
                            t = ts.GetTask(taskName);

                            //Remove the task from Root folder
                            ts.RootFolder.DeleteTask(taskName, false);
                        }
                        scheduledJobModel.Enqueued = false;
                        scheduledJobModel.ScheduledTime = NOT_SET;
                        scheduledJobModel.JobStatus = JobStatus.Disabled;
                        //cell.EditingCellFormattedValue = false;

                        if (t != null)
                            MessageBox.Show("Job successfully removed from the Windows scheduled tasks.");
                    }
                }
            }

            //Run now functionality
            if (e.ColumnIndex == jobsDataGridView.Columns["Run"].Index && e.RowIndex >= 0)
            {
                scheduledJobModel.Job.ExceuteJob();
            }

            if (e.ColumnIndex == jobsDataGridView.Columns["LogFile"].Index && e.RowIndex >= 0)
            {
                string filepath = scheduledJobModel.Job.LogFilePath;
                if (File.Exists(filepath))
                {
                    System.Diagnostics.Process.Start(filepath);
                }
            }

            jobsDataGridView.Refresh();
        }
示例#20
0
 /// <summary>
 /// Saves the specified sections of the security descriptor associated with this <see cref="T:System.Security.AccessControl.ObjectSecurity" /> object to permanent storage. We recommend that the values of the <paramref name="includeSections" /> parameters passed to the constructor and persist methods be identical. For more information, see Remarks.
 /// </summary>
 /// <param name="name">The name used to retrieve the persisted information.</param>
 /// <param name="includeSections">One of the <see cref="T:System.Security.AccessControl.AccessControlSections" /> enumeration values that specifies the sections of the security descriptor (access rules, audit rules, owner, primary group) of the securable object to save.</param>
 protected override void Persist([NotNull] string name, AccessControlSections includeSections = Task.defaultAccessControlSections)
 {
     using (var ts = new TaskService())
     {
         var task = ts.GetTask(name);
         Persist(task, includeSections);
     }
 }
 /// <summary>
 /// Saves the specified sections of the security descriptor associated with this <see cref="T:System.Security.AccessControl.ObjectSecurity" /> object to permanent storage. We recommend that the values of the <paramref name="includeSections" /> parameters passed to the constructor and persist methods be identical. For more information, see Remarks.
 /// </summary>
 /// <param name="name">The name used to retrieve the persisted information.</param>
 /// <param name="includeSections">One of the <see cref="T:System.Security.AccessControl.AccessControlSections" /> enumeration values that specifies the sections of the security descriptor (access rules, audit rules, owner, primary group) of the securable object to save.</param>
 protected override void Persist(string name, AccessControlSections includeSections = AccessControlSections.Access | AccessControlSections.Group | AccessControlSections.Owner)
 {
     using (var ts = new TaskService())
     {
         var task = ts.GetTask(name);
         Persist(task, includeSections);
     }
 }
示例#22
0
        /// <summary>
        /// Gets the named registered task from the collection.
        /// </summary>
        /// <param name="name">The name of the registered task to be retrieved.</param>
        /// <returns>A <see cref="Task"/> instance that contains the requested context.</returns>
        public Task this[string name]
        {
            get
            {
                if (v2Coll != null)
                {
                    return(Task.CreateTask(svc, v2Coll[name]));
                }

                Task v1Task = svc.GetTask(name);
                if (v1Task != null)
                {
                    return(v1Task);
                }

                throw new ArgumentOutOfRangeException(nameof(name));
            }
        }
示例#23
0
 /// <summary>
 /// Gets an IEnumerator instance for this collection.
 /// </summary>
 /// <returns>An enumerator.</returns>
 public IEnumerator <RunningTask> GetEnumerator()
 {
     if (v2Coll != null)
     {
         return(new ComEnumerator <RunningTask, V2Interop.IRunningTask>(() => v2Coll.Count, (object o) => v2Coll[o], o =>
         {
             V2Interop.IRegisteredTask task = null;
             try { task = TaskService.GetTask(svc.v2TaskService, o.Path); } catch { }
             return task == null ? null : new RunningTask(svc, task, o);
         }));
     }
     return(new V1RunningTaskEnumerator(svc));
 }
示例#24
0
 /// <summary>
 /// Gets an IEnumerator instance for this collection.
 /// </summary>
 /// <returns>An enumerator.</returns>
 public IEnumerator <RunningTask> GetEnumerator()
 {
     if (v2Coll != null)
     {
         return(new ComEnumerator <RunningTask, V2Interop.IRunningTaskCollection>(v2Coll, o =>
         {
             var irt = (V2Interop.IRunningTask)o;
             V2Interop.IRegisteredTask task = null;
             try { task = TaskService.GetTask(svc.v2TaskService, irt.Path); } catch { }
             return task == null ? null : new RunningTask(svc, task, irt);
         }));
     }
     return(new V1RunningTaskEnumerator(svc));
 }
示例#25
0
        /// <summary>
        /// Gets the specified running task from the collection.
        /// </summary>
        /// <param name="index">The index of the running task to be retrieved.</param>
        /// <returns>A <see cref="RunningTask"/> instance.</returns>
        public RunningTask this[int index]
        {
            get
            {
                if (v2Coll != null)
                {
                    V2Interop.IRunningTask irt = v2Coll[++index];
                    return(new RunningTask(svc, TaskService.GetTask(svc.v2TaskService, irt.Path), irt));
                }

                int i = 0;
                V1RunningTaskEnumerator v1Enum = new V1RunningTaskEnumerator(svc);
                while (v1Enum.MoveNext())
                {
                    if (i++ == index)
                    {
                        return(v1Enum.Current);
                    }
                }
                throw new ArgumentOutOfRangeException(nameof(index));
            }
        }
示例#26
0
 private Microsoft.Win32.TaskScheduler.Task CreateNewScheduledTask()
 {
     using (TaskService ts = new TaskService())
     {
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = TaskName;
         td.Principal.LogonType = TaskLogonType.InteractiveToken;
         td.Actions.Add(new ExecAction(this.Executable, this.Parameters, null));
         ts.RootFolder.RegisterTaskDefinition(m_internalTaskName, td);
         Microsoft.Win32.TaskScheduler.Task t = ts.GetTask(m_internalTaskName);
         return t;
     }
 }