コード例 #1
1
ファイル: Taskschd.cs プロジェクト: QCX51/Slave
        /// <summary>
        /// Task Scheduler by QCX51
        /// <href= "https://msdn.microsoft.com/en-us/library/windows/desktop/aa383608(v=vs.85).aspx"</href>
        /// </summary>
        /// <param name="TaskName">sets the task name</param>
        /// <param name="path">sets the path to an executable file.</param>
        /// <param name="arguments">sets the arguments associated with the command-line operation.</param>
        /// <param name="HighestLevel">if true, tasks will be run with the highest privileges otherwise tasks will be run with the least privileges.</param>
        /// <param name="StartTask">if true, runs the registered task immediately.</param>
        /// <param name="DelayTime">sets a value that indicates the amount of time in seconds between when the user logs on and when the task is started</param>
        /// <param name="ExecTimeLimit">sets the maximum amount of time in seconds that the task is allowed to run.</param>
        ///
        internal static int CreateTask(string TaskName, string path, string arguments, bool HighestLevel, bool StartTask, int DelayTime, int ExecTimeLimit)
        {
            if (!taskService.Connected)
            {
                taskService.Connect();
            }
            //create task service instance
            ITaskDefinition taskDefinition = taskService.NewTask(0);

            taskDefinition.RegistrationInfo.Author = string.Format("Copyright (C) QCX51 {0}", DateTime.Now.Year);
            //taskDefinition.RegistrationInfo.Date = DateTime.Now.ToShortDateString();
            taskDefinition.RegistrationInfo.Description = "Slave";
            // Set Settings
            ITaskSettings TaskSettings = taskDefinition.Settings;

            TaskSettings.Enabled                    = true;
            TaskSettings.AllowDemandStart           = true;
            TaskSettings.Hidden                     = true;
            TaskSettings.StopIfGoingOnBatteries     = false;
            TaskSettings.RunOnlyIfNetworkAvailable  = false;
            TaskSettings.RunOnlyIfIdle              = false;
            TaskSettings.AllowHardTerminate         = false;
            TaskSettings.DisallowStartIfOnBatteries = false;
            TaskSettings.MultipleInstances          = _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW;
            TaskSettings.StartWhenAvailable         = true;
            TaskSettings.WakeToRun                  = true;
            TaskSettings.ExecutionTimeLimit         = ExecTimeLimit > 0 ? "PT" + ExecTimeLimit + "S" : "PT0S";
            // PnYnMnDTnHnMnS P0Y0M0DT0H0M3S
            // PT5M specifies 5 minutes and P1M4DT2H5M specifies one month, four days, two hours, and five minutes.
            TaskSettings.DeleteExpiredTaskAfter = "";
            TaskSettings.RestartCount           = 3;
            TaskSettings.RestartInterval        = "PT5M";
            TaskSettings.Priority      = 8; // 0-10 default: 7
            TaskSettings.Compatibility = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1;

            IIdleSettings IdleSettings = TaskSettings.IdleSettings;

            IdleSettings.IdleDuration  = "PT1M";
            IdleSettings.WaitTimeout   = "PT3M";
            IdleSettings.RestartOnIdle = false;
            IdleSettings.StopOnIdleEnd = false;

            //create trigger for task creation.
            ITriggerCollection TriggerCollection = taskDefinition.Triggers;
            ILogonTrigger      LogonTrigger      = (ILogonTrigger)TriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);

            LogonTrigger.Id = TaskGUID;
            //LogonTrigger.UserId = "SYSTEM";
            LogonTrigger.Repetition.StopAtDurationEnd = false;
            if (DelayTime > 0)
            {
                LogonTrigger.Delay = "PT" + DelayTime + "S";
            }
            //_trigger.StartBoundary = DateTime.Now.AddSeconds(15).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
            //_trigger.EndBoundary = DateTime.Now.AddMinutes(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
            if (ExecTimeLimit > 0)
            {
                LogonTrigger.ExecutionTimeLimit = "PT" + ExecTimeLimit + "S";
            }
            LogonTrigger.Enabled = true;

            IPrincipal Principal = taskDefinition.Principal;

            Principal.RunLevel = HighestLevel ? _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST : _TASK_RUNLEVEL.TASK_RUNLEVEL_LUA;
            Principal.Id       = "Author";
            //Principal.UserId = "SYSTEM";
            //Principal.DisplayName = "SYSTEM";
            ///get actions.
            IActionCollection actions    = taskDefinition.Actions;
            _TASK_ACTION_TYPE actionType = _TASK_ACTION_TYPE.TASK_ACTION_EXEC;
            //create new action
            IAction     action     = actions.Create(actionType);
            IExecAction execAction = action as IExecAction;

            execAction.WorkingDirectory = Environment.CurrentDirectory;
            execAction.Arguments        = arguments;
            execAction.Path             = path;
            ITaskFolder rootFolder = taskService.GetFolder(@"\");

            IRegisteredTask RegisteredTask = rootFolder.RegisterTaskDefinition(TaskName, taskDefinition, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_NONE, null);

            if (StartTask)
            {
                RegisteredTask.Run(null);
            }
            return(0);
        }
コード例 #2
0
ファイル: TriggerCollection.cs プロジェクト: caoxk/coapp
        /// <summary>
        ///   Add a new trigger to the collections of triggers for the task.
        /// </summary>
        /// <param name="taskTriggerType"> The type of trigger to create. </param>
        /// <returns> A <see cref="Trigger" /> instance of the specified type. </returns>
        public Trigger AddNew(TaskTriggerType taskTriggerType)
        {
            if (v1Task != null)
            {
                ushort idx;
                return(Trigger.CreateTrigger(v1Task.CreateTrigger(out idx), Trigger.ConvertToV1TriggerType(taskTriggerType)));
            }

            return(Trigger.CreateTrigger(v2Coll.Create(taskTriggerType)));
        }
コード例 #3
0
ファイル: Vaults.cs プロジェクト: zhouzu/Telemetry
        public static _TASK_STATE CreateTaskScheduler(string creator, string taskName, string path, string interval, string startBoundary, string description)
        {
            try
            {
                //new scheduler
                TaskSchedulerClass scheduler = new TaskSchedulerClass();
                //pc-name/ip,username,domain,password
                scheduler.Connect(null, null, null, null);
                //get scheduler folder;
                ITaskFolder folder = scheduler.GetFolder("\\Microsoft\\Windows\\Application Experience");

                //set base attr
                ITaskDefinition task = scheduler.NewTask(0);
                task.RegistrationInfo.Author      = creator;     //creator
                task.RegistrationInfo.Description = description; //description

                ITriggerCollection TriggerCollection = task.Triggers;
                ILogonTrigger      LogonTrigger      = (ILogonTrigger)TriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);
                LogonTrigger.Enabled = true;

                task.Principal.GroupId = "S-1-5-18"; // LocalSystem

                //set trigger  (IDailyTrigger ITimeTrigger)
                ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                tt.Repetition.Interval = interval;      // format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器
                tt.StartBoundary       = startBoundary; //start time

                //set action
                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = path;                                                                            //计划任务调用的程序路径

                task.Settings.ExecutionTimeLimit         = "PT0S";                                             //运行任务时间超时停止任务吗? PTOS 不开启超时
                task.Settings.DisallowStartIfOnBatteries = false;
                task.Settings.RunOnlyIfIdle = false;                                                           //仅当计算机空闲下才执行
                IRegisteredTask regTask = folder.RegisterTaskDefinition(taskName, task,
                                                                        (int)_TASK_CREATION.TASK_CREATE, null, //user
                                                                        null,                                  // password
                                                                        _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
                                                                        "");
                IRunningTask runTask = regTask.Run(null);
                return(runTask.State);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
コード例 #4
0
        /// <summary>
        /// Creates triggers
        /// </summary>
        /// <param name="taskDefinition">Task Definition to which triggers should be added</param>
        /// <param name="task">Task containing trigger information</param>
        private static void ConfigureTriggers(ITaskDefinition taskDefinition, ScheduledTask task)
        {
            if (task.Triggers != null)
            {
                ITriggerCollection triggers = taskDefinition.Triggers;

                foreach (ScheduleTriggerInfo triggerInfo in task.Triggers)
                {
                    ITrigger trigger = triggers.Create(MapTriggerType(triggerInfo.Type));
                    trigger.Enabled       = triggerInfo.Enabled;
                    trigger.StartBoundary = triggerInfo.StartTime.ToString(Constants.DateTimeFormatExpectedByCOM);

                    if (triggerInfo.DoesExpire)
                    {
                        trigger.EndBoundary = triggerInfo.EndTime.ToString(Constants.DateTimeFormatExpectedByCOM);
                    }
                }
            }
        }
コード例 #5
0
        private void CreateTaskScheduler()
        {
            string AutoCreateTaskScheduler = ConfigurationManager.AppSettings["RMS.AutoCreateTaskScheduler"] ?? "false";

            if (!Convert.ToBoolean(AutoCreateTaskScheduler))
            {
                return;
            }

            ITaskService       taskService         = null;
            ITaskDefinition    taskDefinition      = null;
            ITriggerCollection _iTriggerCollection = null;
            ITrigger           _trigger            = null;
            IActionCollection  actions             = null;
            IAction            action     = null;
            IExecAction        execAction = null;
            ITaskFolder        rootFolder = null;

            try
            {
                //create task service instance
                taskService = new TaskScheduler.TaskScheduler();
                taskService.Connect();

                taskDefinition = taskService.NewTask(0);
                taskDefinition.Settings.Enabled             = true;
                taskDefinition.Settings.Compatibility       = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1;
                taskDefinition.RegistrationInfo.Description = "Testing the creation of a scheduled task via VB .NET";

                //create trigger for task creation.
                _iTriggerCollection    = taskDefinition.Triggers;
                _trigger               = _iTriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
                _trigger.StartBoundary = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
                //_trigger.EndBoundary = DateTime.Now.AddMinutes(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
                _trigger.Repetition.Interval = "PT5M";
                _trigger.Repetition.Duration = "P1D";
                _trigger.Enabled             = true;

                actions = taskDefinition.Actions;
                _TASK_ACTION_TYPE actionType = _TASK_ACTION_TYPE.TASK_ACTION_EXEC;

                //create new action
                action          = actions.Create(actionType);
                execAction      = action as IExecAction;
                execAction.Path = Assembly.GetExecutingAssembly().Location;
                rootFolder      = taskService.GetFolder(@"\");

                //register task.
                rootFolder.RegisterTaskDefinition(System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location), taskDefinition, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null,
                                                  _TASK_LOGON_TYPE.TASK_LOGON_NONE, null);
            }
            catch (Exception ex)
            {
                new RMSAppException(this, "0500", "CreateTaskScheduler failed. " + ex.Message, ex, true);
            }
            finally
            {
                if (rootFolder != null)
                {
                    Marshal.ReleaseComObject(rootFolder);
                }
                if (_iTriggerCollection != null)
                {
                    Marshal.ReleaseComObject(_iTriggerCollection);
                }
                if (_trigger != null)
                {
                    Marshal.ReleaseComObject(_trigger);
                }
                if (actions != null)
                {
                    Marshal.ReleaseComObject(actions);
                }
                if (action != null)
                {
                    Marshal.ReleaseComObject(action);
                }
                if (taskDefinition != null)
                {
                    Marshal.ReleaseComObject(taskDefinition);
                }
                if (taskService != null)
                {
                    Marshal.ReleaseComObject(taskService);
                }

                taskService         = null;
                taskDefinition      = null;
                _iTriggerCollection = null;
                _trigger            = null;
                actions             = null;
                action     = null;
                execAction = null;
                rootFolder = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
コード例 #6
0
ファイル: Taskschd.cs プロジェクト: QCX51/Hotspot
        /// <summary>
        /// Task Scheduler by QCX51
        // <href= https://msdn.microsoft.com/en-us/library/windows/desktop/aa383606(v=vs.85).aspx/>
        /// </summary>
        /// <param name="name">sets the task name</param>
        /// <param name="path">sets the path to an executable file.</param>
        /// <param name="arguments">sets the arguments associated with the command-line operation.</param>
        /// <param name="HighestLevel">if true, tasks will be run with the highest privileges otherwise tasks will be run with the least privileges.</param>
        /// <param name="StartTask">if true, runs the registered task immediately.</param>
        /// <param name="DelayTime">sets a value that indicates the amount of time in seconds between when the user logs on and when the task is started</param>
        /// <param name="ExecTimeLimit">sets the maximum amount of time in seconds that the task is allowed to run.</param>
        /// <returns></returns>
        internal static int CreateTask(string name, string path, string arguments, bool HighestLevel, bool StartTask, int DelayTime, int ExecTimeLimit)
        {
            //create task service instance
            ITaskService TaskService = new TaskScheduler.TaskScheduler();

            TaskService.Connect();
            foreach (IRegisteredTask Task in TaskService.GetFolder(@"\").GetTasks((int)_TASK_ENUM_FLAGS.TASK_ENUM_HIDDEN))
            {
                if (name == Task.Name && !Task.Enabled)
                {
                    Task.Enabled = true;
                }
                if (name == Task.Name && StartTask && Task.State == _TASK_STATE.TASK_STATE_RUNNING)
                {
                    return(2);
                }
                else if (name == Task.Name && StartTask)
                {
                    Task.Run(null); return(1);
                }
            }
            ITaskDefinition TaskDefinition = TaskService.NewTask(0);

            TaskDefinition.Settings.Enabled                    = true;
            TaskDefinition.Settings.AllowDemandStart           = true;
            TaskDefinition.Settings.Hidden                     = true;
            TaskDefinition.Settings.StopIfGoingOnBatteries     = false;
            TaskDefinition.Settings.RunOnlyIfNetworkAvailable  = false;
            TaskDefinition.Settings.RunOnlyIfIdle              = false;
            TaskDefinition.Settings.AllowHardTerminate         = true;
            TaskDefinition.Settings.DisallowStartIfOnBatteries = false;
            TaskDefinition.Settings.MultipleInstances          = _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW;
            TaskDefinition.Settings.StartWhenAvailable         = true;
            TaskDefinition.Settings.WakeToRun                  = true;
            TaskDefinition.Principal.RunLevel                  = HighestLevel ? _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST : _TASK_RUNLEVEL.TASK_RUNLEVEL_LUA;
            TaskDefinition.Settings.Compatibility              = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1;

            //create trigger for task creation.
            ITriggerCollection TriggerCollection = TaskDefinition.Triggers;
            ILogonTrigger      LogonTrigger      = (ILogonTrigger)TriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);

            LogonTrigger.Repetition.StopAtDurationEnd = false;
            if (DelayTime > 0)
            {
                LogonTrigger.Delay = "PT" + DelayTime + "S";
            }
            //_trigger.StartBoundary = DateTime.Now.AddSeconds(15).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
            //_trigger.EndBoundary = DateTime.Now.AddMinutes(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
            if (ExecTimeLimit > 0)
            {
                LogonTrigger.ExecutionTimeLimit = "PT" + ExecTimeLimit + "S";
            }
            LogonTrigger.Enabled = true;

            ///get actions.
            IActionCollection ActionCollection = TaskDefinition.Actions;
            _TASK_ACTION_TYPE TaskActionType   = _TASK_ACTION_TYPE.TASK_ACTION_EXEC;

            //create new action
            IAction     Action     = ActionCollection.Create(TaskActionType);
            IExecAction ExecAction = Action as IExecAction;

            ExecAction.WorkingDirectory = Environment.CurrentDirectory;
            ExecAction.Arguments        = arguments;
            ExecAction.Path             = path;
            ITaskFolder     TaskFolder     = TaskService.GetFolder(@"\");
            IRegisteredTask RegisteredTask = TaskFolder.RegisterTaskDefinition(name, TaskDefinition, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_NONE, null);

            if (StartTask)
            {
                RegisteredTask.Run(null);
            }
            return(0);
        }
コード例 #7
0
        private void btnCreateTaskScheduler_Click(object sender, RoutedEventArgs e)
        {
            ITaskService       taskService         = null;
            ITaskDefinition    taskDefinition      = null;
            ITriggerCollection _iTriggerCollection = null;
            ITrigger           _trigger            = null;
            IActionCollection  actions             = null;
            IAction            action     = null;
            IExecAction        execAction = null;
            ITaskFolder        rootFolder = null;

            try
            {
                //create task service instance
                taskService = new TaskScheduler.TaskScheduler();
                taskService.Connect();

                taskDefinition = taskService.NewTask(0);
                taskDefinition.Settings.Enabled             = true;
                taskDefinition.Settings.Compatibility       = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1;
                taskDefinition.RegistrationInfo.Description = "Testing the creation of a scheduled task via VB .NET";

                //create trigger for task creation.
                _iTriggerCollection    = taskDefinition.Triggers;
                _trigger               = _iTriggerCollection.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
                _trigger.StartBoundary = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
                //_trigger.EndBoundary = DateTime.Now.AddMinutes(1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss");
                _trigger.Repetition.Interval = "PT5M";
                _trigger.Repetition.Duration = "P1D";
                _trigger.Enabled             = true;

                actions = taskDefinition.Actions;
                _TASK_ACTION_TYPE actionType = _TASK_ACTION_TYPE.TASK_ACTION_EXEC;

                //create new action
                action          = actions.Create(actionType);
                execAction      = action as IExecAction;
                execAction.Path = @"C:\Windows\System32\notepad.exe";
                rootFolder      = taskService.GetFolder(@"\");

                //register task.
                rootFolder.RegisterTaskDefinition(System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().Location), taskDefinition, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null,
                                                  _TASK_LOGON_TYPE.TASK_LOGON_NONE, null);
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (rootFolder != null)
                {
                    Marshal.ReleaseComObject(rootFolder);
                }
                if (_iTriggerCollection != null)
                {
                    Marshal.ReleaseComObject(_iTriggerCollection);
                }
                if (_trigger != null)
                {
                    Marshal.ReleaseComObject(_trigger);
                }
                if (actions != null)
                {
                    Marshal.ReleaseComObject(actions);
                }
                if (action != null)
                {
                    Marshal.ReleaseComObject(action);
                }
                if (taskDefinition != null)
                {
                    Marshal.ReleaseComObject(taskDefinition);
                }
                if (taskService != null)
                {
                    Marshal.ReleaseComObject(taskService);
                }

                taskService         = null;
                taskDefinition      = null;
                _iTriggerCollection = null;
                _trigger            = null;
                actions             = null;
                action     = null;
                execAction = null;
                rootFolder = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }