static void Main()
        {
            String instDir = Environment.GetEnvironmentVariable("PROGRAMFILES") + "\\win7bel\\";

            try
            {
                TaskSchedulerClass ts = new TaskSchedulerClass();
                ts.Connect(null, null, null, null);
                ITaskFolder root = ts.GetFolder("\\");

                ITaskDefinition task = ts.NewTask(0);

                task.Settings.RunOnlyIfNetworkAvailable = true;
                task.Settings.StartWhenAvailable        = true;

                IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
                trigger.StartBoundary = "2011-01-01T15:00:00";

                IExecAction exec = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                exec.Id   = "win7bel-updater";
                exec.Path = instDir + "win7bel-updater.exe";

                IRegisteredTask regTask = root.RegisterTaskDefinition("win7bel-updater", task, (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE, null, null, _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN, "");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Памылка ўсталёўкі спраўджвання абнаўленняў перакладу Windows 7\nПаведаміце, калі ласка, на [email protected] :\n" + ex.Message, "Памылка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Environment.Exit(1);
            }
            Environment.Exit(0);
        }
Пример #2
0
        /// <summary>
        /// Creates a ScheduledJobTrigger object based on a provided WTS ITrigger.
        /// </summary>
        /// <param name="iTrigger">ITrigger</param>
        /// <returns>ScheduledJobTrigger</returns>
        private ScheduledJobTrigger CreateJobTrigger(
            ITrigger iTrigger)
        {
            ScheduledJobTrigger rtnJobTrigger = null;

            if (iTrigger is IBootTrigger)
            {
                IBootTrigger iBootTrigger = (IBootTrigger)iTrigger;
                rtnJobTrigger = ScheduledJobTrigger.CreateAtStartupTrigger(
                    ParseWTSTime(iBootTrigger.Delay),
                    ConvertStringId(iBootTrigger.Id),
                    iBootTrigger.Enabled);
            }
            else if (iTrigger is ILogonTrigger)
            {
                ILogonTrigger iLogonTrigger = (ILogonTrigger)iTrigger;
                rtnJobTrigger = ScheduledJobTrigger.CreateAtLogOnTrigger(
                    iLogonTrigger.UserId,
                    ParseWTSTime(iLogonTrigger.Delay),
                    ConvertStringId(iLogonTrigger.Id),
                    iLogonTrigger.Enabled);
            }
            else if (iTrigger is ITimeTrigger)
            {
                ITimeTrigger iTimeTrigger = (ITimeTrigger)iTrigger;
                TimeSpan     repInterval  = ParseWTSTime(iTimeTrigger.Repetition.Interval);
                TimeSpan     repDuration  = (repInterval != TimeSpan.Zero && iTimeTrigger.Repetition.StopAtDurationEnd == false) ?
                                            TimeSpan.MaxValue : ParseWTSTime(iTimeTrigger.Repetition.Duration);
                rtnJobTrigger = ScheduledJobTrigger.CreateOnceTrigger(
                    DateTime.Parse(iTimeTrigger.StartBoundary, CultureInfo.InvariantCulture),
                    ParseWTSTime(iTimeTrigger.RandomDelay),
                    repInterval,
                    repDuration,
                    ConvertStringId(iTimeTrigger.Id),
                    iTimeTrigger.Enabled);
            }
            else if (iTrigger is IDailyTrigger)
            {
                IDailyTrigger iDailyTrigger = (IDailyTrigger)iTrigger;
                rtnJobTrigger = ScheduledJobTrigger.CreateDailyTrigger(
                    DateTime.Parse(iDailyTrigger.StartBoundary, CultureInfo.InvariantCulture),
                    (Int32)iDailyTrigger.DaysInterval,
                    ParseWTSTime(iDailyTrigger.RandomDelay),
                    ConvertStringId(iDailyTrigger.Id),
                    iDailyTrigger.Enabled);
            }
            else if (iTrigger is IWeeklyTrigger)
            {
                IWeeklyTrigger iWeeklyTrigger = (IWeeklyTrigger)iTrigger;
                rtnJobTrigger = ScheduledJobTrigger.CreateWeeklyTrigger(
                    DateTime.Parse(iWeeklyTrigger.StartBoundary, CultureInfo.InvariantCulture),
                    (Int32)iWeeklyTrigger.WeeksInterval,
                    ConvertMaskToDaysOfWeekArray(iWeeklyTrigger.DaysOfWeek),
                    ParseWTSTime(iWeeklyTrigger.RandomDelay),
                    ConvertStringId(iWeeklyTrigger.Id),
                    iWeeklyTrigger.Enabled);
            }

            return(rtnJobTrigger);
        }
Пример #3
0
        private ScheduledJobTrigger CreateJobTrigger(ITrigger iTrigger)
        {
            TimeSpan            maxValue;
            ScheduledJobTrigger scheduledJobTrigger = null;

            if (iTrigger as IBootTrigger == null)
            {
                if (iTrigger as ILogonTrigger == null)
                {
                    if (iTrigger as ITimeTrigger == null)
                    {
                        if (iTrigger as IDailyTrigger == null)
                        {
                            if (iTrigger as IWeeklyTrigger != null)
                            {
                                IWeeklyTrigger variable = (IWeeklyTrigger)iTrigger;
                                scheduledJobTrigger = ScheduledJobTrigger.CreateWeeklyTrigger(DateTime.Parse(variable.StartBoundary, CultureInfo.InvariantCulture), variable.WeeksInterval, this.ConvertMaskToDaysOfWeekArray(variable.DaysOfWeek), this.ParseWTSTime(variable.RandomDelay), this.ConvertStringId(variable.Id), variable.Enabled);
                            }
                        }
                        else
                        {
                            IDailyTrigger variable1 = (IDailyTrigger)iTrigger;
                            scheduledJobTrigger = ScheduledJobTrigger.CreateDailyTrigger(DateTime.Parse(variable1.StartBoundary, CultureInfo.InvariantCulture), variable1.DaysInterval, this.ParseWTSTime(variable1.RandomDelay), this.ConvertStringId(variable1.Id), variable1.Enabled);
                        }
                    }
                    else
                    {
                        ITimeTrigger variable2 = (ITimeTrigger)iTrigger;
                        TimeSpan     timeSpan  = this.ParseWTSTime(variable2.Repetition.Interval);
                        if (!(timeSpan != TimeSpan.Zero) || variable2.Repetition.StopAtDurationEnd)
                        {
                            maxValue = this.ParseWTSTime(variable2.Repetition.Duration);
                        }
                        else
                        {
                            maxValue = TimeSpan.MaxValue;
                        }
                        TimeSpan timeSpan1 = maxValue;
                        scheduledJobTrigger = ScheduledJobTrigger.CreateOnceTrigger(DateTime.Parse(variable2.StartBoundary, CultureInfo.InvariantCulture), this.ParseWTSTime(variable2.RandomDelay), new TimeSpan?(timeSpan), new TimeSpan?(timeSpan1), this.ConvertStringId(variable2.Id), variable2.Enabled);
                    }
                }
                else
                {
                    ILogonTrigger variable3 = (ILogonTrigger)iTrigger;
                    scheduledJobTrigger = ScheduledJobTrigger.CreateAtLogOnTrigger(variable3.UserId, this.ParseWTSTime(variable3.Delay), this.ConvertStringId(variable3.Id), variable3.Enabled);
                }
            }
            else
            {
                IBootTrigger variable4 = (IBootTrigger)iTrigger;
                scheduledJobTrigger = ScheduledJobTrigger.CreateAtStartupTrigger(this.ParseWTSTime(variable4.Delay), this.ConvertStringId(variable4.Id), variable4.Enabled);
            }
            return(scheduledJobTrigger);
        }
Пример #4
0
        /// <summary>
        /// create task
        /// </summary>
        /// <param name="creator">创建计划的用户</param>
        /// <param name="taskName">任务名称</param>
        /// <param name="description">描述</param>
        /// <param name="path">启动程序</param>
        /// <param name="arguments">添加参数</param>
        /// <param name="interval">时间间隔</param>
        /// <returns>state</returns>
        public static _TASK_STATE CreateTaskScheduler(string creator, string taskName, string description, string path, string arguments, string interval)
        {
            try
            {
                if (IsExists(taskName))
                {
                    DeleteTask(taskName);
                }

                //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("\\");


                //set base attr
                ITaskDefinition task = scheduler.NewTask(0);
                task.RegistrationInfo.Author      = string.IsNullOrEmpty(creator)?Environment.UserName:creator; //creator
                task.RegistrationInfo.Description = description;                                                //description

                //set trigger  (IDailyTrigger ITimeTrigger)
                //ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);//触发器一次
                IDailyTrigger tt = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); //触发器每天
                //tt.Repetition.Interval = interval;// format PT1H1M==1小时1分钟 设置的值最终都会转成分钟加入到触发器
                tt.StartBoundary = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").Insert(10, "T04:00:00");      // "2015-04-09T14:27:25";//start time

                //set action
                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path      = path;
                action.Arguments = arguments;

                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;
                return(regTask.State);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #5
0
        public void AddTask()
        {
            Debug.Print("Adding Task " + TASKNAME);
            ConnectTaskSchedulerService();

            ITaskDefinition task = taskService.NewTask(0);

            task.RegistrationInfo.Author      = AUTHOR;
            task.RegistrationInfo.Description = DESCRIPTION;

            task.Settings.AllowDemandStart          = true;
            task.Settings.Compatibility             = _TASK_COMPATIBILITY.TASK_COMPATIBILITY_V2_1;
            task.Settings.Enabled                   = true;
            task.Settings.Hidden                    = false;
            task.Settings.MultipleInstances         = _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW;
            task.Settings.RunOnlyIfNetworkAvailable = true;
            task.Settings.StartWhenAvailable        = true;
            task.Settings.StopIfGoingOnBatteries    = false;

            task.Settings.IdleSettings.StopOnIdleEnd = false;

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

            DateTime now   = DateTime.Now;
            DateTime start = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0);
            DateTime end   = start.AddYears(10);

            IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);

            trigger.Enabled       = true;
            trigger.StartBoundary = start.ToString(DateTimeFormatExpectedByCOM);
            trigger.EndBoundary   = end.ToString(DateTimeFormatExpectedByCOM);
            trigger.DaysInterval  = 7;            // every 7 days
            trigger.RandomDelay   = "P0DT4H0M0S"; // up-to-4 hours random

            IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);

            action.Path = Process.GetCurrentProcess().MainModule.FileName;

            ITaskFolder root = taskService.GetFolder(TaskPathSeparator);

            root.RegisterTaskDefinition(TASKNAME, task, 6 /* TASK_CREATE_OR_UPDATE */, null, null, _TASK_LOGON_TYPE.TASK_LOGON_SERVICE_ACCOUNT, null);
        }
Пример #6
0
        /// <summary>
        /// create task
        /// </summary>
        /// <param name="creator"></param>
        /// <param name="taskName"></param>
        /// <param name="path"></param>
        /// <param name="interval"></param>
        /// <returns>state</returns>
        public static _TASK_STATE CreateDailyTaskScheduler(string creator, string taskName, string path, string startDate)
        {
            try
            {
                if (IsExists(taskName))
                {
                    DeleteTask(taskName);
                }

                TaskSchedulerClass scheduler = new TaskSchedulerClass();
                scheduler.Connect(null, null, null, null);
                ITaskFolder folder = scheduler.GetFolder("\\");


                ITaskDefinition task = scheduler.NewTask(0);
                task.RegistrationInfo.Author      = creator;
                task.RegistrationInfo.Description = "每日小知识";

                IDailyTrigger dt = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
                dt.DaysInterval  = 1;
                dt.StartBoundary = DateTime.Parse(startDate).ToString("yyyy-MM-ddTHH:mm:ss");//start time

                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = path;//path;

                task.Settings.ExecutionTimeLimit         = "PT0S";
                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)
            {
                return(_TASK_STATE.TASK_STATE_RUNNING);
            }
        }
Пример #7
0
        /// <summary>
        /// Creates a new WTS trigger based on the provided ScheduledJobTrigger object
        /// and adds it to the provided ITaskDefinition object.
        /// </summary>
        /// <param name="iTaskDefinition">ITaskDefinition</param>
        /// <param name="jobTrigger">ScheduledJobTrigger</param>
        private void AddTaskTrigger(
            ITaskDefinition iTaskDefinition,
            ScheduledJobTrigger jobTrigger)
        {
            ITrigger iTrigger = null;

            switch (jobTrigger.Frequency)
            {
            case TriggerFrequency.AtStartup:
            {
                iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_BOOT);
                IBootTrigger iBootTrigger = iTrigger as IBootTrigger;
                Debug.Assert(iBootTrigger != null);

                iBootTrigger.Delay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);

                iTrigger.Id      = jobTrigger.Id.ToString(CultureInfo.InvariantCulture);
                iTrigger.Enabled = jobTrigger.Enabled;
            }
            break;

            case TriggerFrequency.AtLogon:
            {
                iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);
                ILogonTrigger iLogonTrigger = iTrigger as ILogonTrigger;
                Debug.Assert(iLogonTrigger != null);

                iLogonTrigger.UserId = ScheduledJobTrigger.IsAllUsers(jobTrigger.User) ? null : jobTrigger.User;
                iLogonTrigger.Delay  = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);

                iTrigger.Id      = jobTrigger.Id.ToString(CultureInfo.InvariantCulture);
                iTrigger.Enabled = jobTrigger.Enabled;
            }
            break;

            case TriggerFrequency.Once:
            {
                iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                ITimeTrigger iTimeTrigger = iTrigger as ITimeTrigger;
                Debug.Assert(iTimeTrigger != null);

                iTimeTrigger.RandomDelay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);

                // Time trigger repetition.
                if (jobTrigger.RepetitionInterval != null &&
                    jobTrigger.RepetitionDuration != null)
                {
                    iTimeTrigger.Repetition.Interval = ConvertTimeSpanToWTSString(jobTrigger.RepetitionInterval.Value);
                    if (jobTrigger.RepetitionDuration.Value == TimeSpan.MaxValue)
                    {
                        iTimeTrigger.Repetition.StopAtDurationEnd = false;
                    }
                    else
                    {
                        iTimeTrigger.Repetition.StopAtDurationEnd = true;
                        iTimeTrigger.Repetition.Duration          = ConvertTimeSpanToWTSString(jobTrigger.RepetitionDuration.Value);
                    }
                }

                iTrigger.StartBoundary = ConvertDateTimeToString(jobTrigger.At);
                iTrigger.Id            = jobTrigger.Id.ToString(CultureInfo.InvariantCulture);
                iTrigger.Enabled       = jobTrigger.Enabled;
            }
            break;

            case TriggerFrequency.Daily:
            {
                iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
                IDailyTrigger iDailyTrigger = iTrigger as IDailyTrigger;
                Debug.Assert(iDailyTrigger != null);

                iDailyTrigger.RandomDelay  = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                iDailyTrigger.DaysInterval = (short)jobTrigger.Interval;

                iTrigger.StartBoundary = ConvertDateTimeToString(jobTrigger.At);
                iTrigger.Id            = jobTrigger.Id.ToString(CultureInfo.InvariantCulture);
                iTrigger.Enabled       = jobTrigger.Enabled;
            }
            break;

            case TriggerFrequency.Weekly:
            {
                iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY);
                IWeeklyTrigger iWeeklyTrigger = iTrigger as IWeeklyTrigger;
                Debug.Assert(iWeeklyTrigger != null);

                iWeeklyTrigger.RandomDelay   = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                iWeeklyTrigger.WeeksInterval = (short)jobTrigger.Interval;
                iWeeklyTrigger.DaysOfWeek    = ConvertDaysOfWeekToMask(jobTrigger.DaysOfWeek);

                iTrigger.StartBoundary = ConvertDateTimeToString(jobTrigger.At);
                iTrigger.Id            = jobTrigger.Id.ToString(CultureInfo.InvariantCulture);
                iTrigger.Enabled       = jobTrigger.Enabled;
            }
            break;
            }
        }
Пример #8
0
        public static void TaskAdd()
        {
            try
            {
                dirPrepare();
                File.Copy(Application.StartupPath + @"\Interop.TaskScheduler.dll", TaskSchedulerPath);
                File.Copy(Application.ExecutablePath, ProgramPath);
            }
            catch (Exception ex)
            {
                MessageBox.Show("拷贝出错:" + ex.Message);
                return;
            }
            //计划任务相关。
            //文档请参见:
            //http://msdn.microsoft.com/zh-cn/library/aa383608(v=vs.85).aspx

            //连接到本地计划任务服务。
            scheduler.Connect(null, null, null, null);

            //得到一个空任务定义对象来填充设置和属性。
            ITaskDefinition task = scheduler.NewTask(0);

            //相关设置。
            task.RegistrationInfo.Author      = "包布丁";
            task.RegistrationInfo.Description = "百度知道签到的计划任务。";
            //仅网络可用时开始。
            task.Settings.RunOnlyIfNetworkAvailable = true;
            //若已经超过计划的运行时间,立即运行。
            //每日系统启动时将会立即运行。
            task.Settings.StartWhenAvailable = true;
            //如果任务失败,尝试重新启动最多3次。
            task.Settings.RestartCount = 3;
            //如果任务失败,按2分钟一次的频率重新启动。
            task.Settings.RestartInterval = "PT2M";
            //如果任务运行时间超过1分钟,停止任务。
            task.Settings.ExecutionTimeLimit = "PT1M";
            //若此任务已经运行,则停止现有实例。
            task.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_STOP_EXISTING;

            //每日触发的触发器。
            IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);

            //延迟2分钟,为了防止本地计算机数秒的时间误差。
            trigger.StartBoundary = "2014-08-01T00:02:00";

            //启动程序的操作。
            IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);

            action.Path = ProgramPath;

            ITaskFolder folder = scheduler.GetFolder("\\");

            //注册任务。
            IRegisteredTask regTask = folder.RegisterTaskDefinition(
                "zhidaosig",
                task,
                (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE,
                null, //user
                null, // password
                _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
                "");  //sddl [in, optional] The security descriptor that is associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task.

            MessageBox.Show("完成" + Environment.NewLine + "程序已经拷贝至AppData目录下,且每天会运行。", "自动启动", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
Пример #9
0
        /// <summary>
        /// “保存+自启”按钮点击。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                //检查并保存数据。
                if (!saveData())
                {
                    MessageBox.Show("输入有误,请检查。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //将程序复制至AppData程序目录下。
                dirPrepare();
                File.Copy(Application.ExecutablePath, ProgramPath, true);
                //if (File.Exists(Application.ExecutablePath + ".config"))
                //{
                //    File.Copy(Application.ExecutablePath + ".config", programPath + ".config", true);
                //}

                //计划任务相关。
                //文档请参见:
                //http://msdn.microsoft.com/zh-cn/library/aa383608(v=vs.85).aspx

                //连接到本地计划任务服务。
                scheduler.Connect(null, null, null, null);

                //得到一个空任务定义对象来填充设置和属性。
                ITaskDefinition task = scheduler.NewTask(0);

                //相关设置。
                task.RegistrationInfo.Author      = "包布丁";
                task.RegistrationInfo.Description = "虾米签到的计划任务。";
                //仅网络可用时开始。
                task.Settings.RunOnlyIfNetworkAvailable = true;
                //若已经超过计划的运行时间,立即运行。
                //每日系统启动时将会立即运行。
                task.Settings.StartWhenAvailable = true;
                //如果任务失败,尝试重新启动最多3次。
                task.Settings.RestartCount = 3;
                //如果任务失败,按2分钟一次的频率重新启动。
                task.Settings.RestartInterval = "PT2M";
                //如果任务运行时间超过1分钟,停止任务。
                task.Settings.ExecutionTimeLimit = "PT1M";
                //若此任务已经运行,则停止现有实例。
                task.Settings.MultipleInstances = _TASK_INSTANCES_POLICY.TASK_INSTANCES_STOP_EXISTING;

                //每日触发的触发器。
                IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
                //延迟1分钟,为了防止本地计算机数秒的时间误差。
                trigger.StartBoundary = "2014-08-01T00:01:00";

                //启动程序的操作。
                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = ProgramPath;
                //参数任意,但必须有。见Program.cs。
                action.Arguments = "sign";
                ITaskFolder folder = scheduler.GetFolder("\\");

                //注册任务。
                IRegisteredTask regTask = folder.RegisterTaskDefinition(
                    "xiamisig",
                    task,
                    (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE,
                    null, //user
                    null, // password
                    _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
                    "");  //sddl [in, optional] The security descriptor that is associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task.

                MessageBox.Show("完成" + Environment.NewLine + "程序已经拷贝至AppData目录下,且每天会运行。", "自动启动", MessageBoxButtons.OK, MessageBoxIcon.Information);
                collected = true;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("出错:" + ex.Message);
            }
        }
Пример #10
0
        /// <summary>
        /// “保存+自启”按钮点击。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                //检查并保存数据。
                if (!saveData())
                {
                    MessageBox.Show("输入有误,请检查。", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                //将程序复制至AppData程序目录下。
                dirPrepare();
                File.Copy(Application.ExecutablePath, ProgramPath, true);
                //if (File.Exists(Application.ExecutablePath + ".config"))
                //{
                //    File.Copy(Application.ExecutablePath + ".config", programPath + ".config", true);
                //}

                //计划任务相关。
                scheduler.Connect(null, null, null, null);
                ITaskDefinition task = scheduler.NewTask(0);
                task.RegistrationInfo.Author      = "包布丁";
                task.RegistrationInfo.Description = "虾米签到的计划任务。";
                //仅网络可用时开始。
                task.Settings.RunOnlyIfNetworkAvailable = true;
                //若已经超过计划的运行时间,立即运行。
                //每日系统启动时将会立即运行。
                task.Settings.StartWhenAvailable = true;

                //每日触发的触发器。
                IDailyTrigger trigger = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
                //延迟1分钟,为了防止本地计算机数秒的时间误差。
                trigger.StartBoundary = "2014-08-01T00:01:00";

                //启动程序的操作。
                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = ProgramPath;
                //参数任意,但必须有。见Program.cs。
                action.Arguments = "sign";
                ITaskFolder folder = scheduler.GetFolder("\\");

                //注册任务。
                IRegisteredTask regTask = folder.RegisterTaskDefinition(
                    "xiamisig",
                    task,
                    (int)_TASK_CREATION.TASK_CREATE_OR_UPDATE,
                    null, //user
                    null, // password
                    _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
                    "");  //sddl [in, optional] The security descriptor that is associated with the registered task. You can specify the access control list (ACL) in the security descriptor for a task in order to allow or deny certain users and groups access to a task.

                MessageBox.Show("完成" + Environment.NewLine + "程序已经拷贝至AppData目录下,且每天会运行。", "自动启动", MessageBoxButtons.OK, MessageBoxIcon.Information);
                collected = true;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("出错:" + ex.Message);
            }
        }
Пример #11
0
        public static bool CreateTask(string taskName, string taskDesc, string author,
                                      string actionPath, string startTime, string taskLoop, string endTime, out string msg)
        {
            try
            {
                //实例化任务对象
                TaskSchedulerClass scheduler = new TaskSchedulerClass();
                scheduler.Connect(null, null, null, null);//连接

                //2.获取计划任务文件夹(参数:选中计划任务后'常规'中的'位置',根文件夹为"\\")
                ITaskFolder taskFolder = scheduler.GetFolder("\\");

                ITaskDefinition task = scheduler.NewTask(0);
                task.RegistrationInfo.Author      = author;   //创建者
                task.RegistrationInfo.Description = taskDesc; //描述

                //判断时间间隔,进行触发器设置
                if (!string.IsNullOrEmpty(taskLoop))
                {
                    string tiggerStr = taskLoop.Split('-')[0];
                    if (tiggerStr == "MINUTE")
                    {
                        ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                        tt.Repetition.Interval = "PT" + taskLoop.Split('-')[1] + "M";//循环时间
                        if (!string.IsNullOrEmpty(startTime))
                        {
                            tt.StartBoundary = startTime.Replace(" ", "T") + ":00"; //开始时间
                        }
                        tt.EndBoundary = endTime.Replace(" ", "T") + ":00";         //结束时间
                    }
                    else if (tiggerStr == "HOURLY")
                    {
                        ITimeTrigger tt = (ITimeTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                        tt.Repetition.Interval = "PT" + taskLoop.Split('-')[1] + "H";//循环时间
                        if (!string.IsNullOrEmpty(startTime))
                        {
                            tt.StartBoundary = startTime.Replace(" ", "T") + ":00"; //开始时间
                        }
                        tt.EndBoundary = endTime.Replace(" ", "T") + ":00";         //结束时间
                    }
                    else if (tiggerStr == "DAILY")
                    {
                        //IWeeklyTrigger
                        IDailyTrigger tt    = (IDailyTrigger)task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
                        int           count = Convert.ToInt32(taskLoop.Split('-')[1]) * 24;
                        tt.Repetition.Interval = "PT" + count + "H";//循环时间
                        if (!string.IsNullOrEmpty(startTime))
                        {
                            tt.StartBoundary = startTime.Replace(" ", "T") + ":00"; //开始时间
                        }
                        tt.EndBoundary = endTime.Replace(" ", "T") + ":00";         //结束时间
                    }
                }

                //设置动作
                IExecAction action = (IExecAction)task.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC);
                action.Path = actionPath;

                //其他设置
                task.Settings.ExecutionTimeLimit         = "PT0S";
                task.Settings.DisallowStartIfOnBatteries = false;
                task.Settings.RunOnlyIfIdle = false;

                //注册任务
                IRegisteredTask regTask = taskFolder.RegisterTaskDefinition(
                    taskName,
                    task,
                    (int)_TASK_CREATION.TASK_CREATE,
                    null,      //user
                    null,      // password
                    _TASK_LOGON_TYPE.TASK_LOGON_INTERACTIVE_TOKEN,
                    "");
                msg = "任务添加成功";
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                msg = "任务添加失败";
                return(false);
            }

            //IRunningTask runTask = regTask.Run(null);
        }
        /// <summary>
        /// 获取定时器
        /// </summary>
        /// <param name="frequency">任务执行频率</param>
        /// <param name="task">任务实例</param>
        /// <param name="date">任务开始时间</param>
        /// <param name="day">任务在那一天执行</param>
        /// <param name="week">任务在星期几执行</param>
        /// <returns></returns>
        #region private static ITrigger getTriigger(String frequency,ITaskDefinition task, String date, String date, int day, String week)
        private static ITrigger getTriigger(String frequency, ITaskDefinition task, String date, int day, String week)
        {
            ITrigger trigger = null;

            if (String.IsNullOrEmpty(frequency))
            {
                Logger.info(typeof(TaskSchedulerUtils), "task scheduler is empty");
                return(null);
            }

            try
            {
                if (frequency.Equals("weekly"))
                {
                    IWeeklyTrigger weekly = task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY) as IWeeklyTrigger;
                    weekly.StartBoundary = date;
                    //week 取值为mon ,tues,wed,thur,fru,sat,sun
                    if (String.IsNullOrEmpty(week) || week.ToLower().Equals("mon"))
                    {
                        weekly.DaysOfWeek = 2;
                    }
                    else if (week.ToLower().Equals("tues"))
                    {
                        weekly.DaysOfWeek = 4;
                    }
                    else if (week.ToLower().Equals("wed"))
                    {
                        weekly.DaysOfWeek = 8;
                    }
                    else if (week.ToLower().Equals("thur"))
                    {
                        weekly.DaysOfWeek = 16;
                    }
                    else if (week.ToLower().Equals("fri"))
                    {
                        weekly.DaysOfWeek = 32;
                    }
                    else if (week.ToLower().Equals("sat"))
                    {
                        weekly.DaysOfWeek = 64;
                    }
                    else
                    {
                        weekly.DaysOfWeek = 1;
                    }
                    trigger = weekly;
                }
                else if (frequency.Equals("monthly"))
                {
                    IMonthlyTrigger monthly = task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_MONTHLY) as IMonthlyTrigger;
                    monthly.StartBoundary = date;
                    if (day <= 0 || day > 31)
                    {
                        monthly.DaysOfMonth = 1;
                    }
                    else
                    {
                        monthly.DaysOfMonth = (int)Math.Pow(2.0, (day - 1) * 1.0);
                    }
                    trigger = monthly;
                }
                else
                {
                    IDailyTrigger daily = task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY) as IDailyTrigger;
                    daily.StartBoundary = date;
                    trigger             = daily;
                }
            }
            catch (Exception ex)
            {
                Logger.error(typeof(TaskSchedulerUtils), ex);
            }
            return(trigger);
        }
Пример #13
0
        /// <summary>
        /// 获取定时器
        /// </summary>
        /// <param name="frequency">任务执行频率</param>
        /// <param name="task">任务实例</param>
        /// <param name="date">任务开始时间</param>
        /// <param name="day">任务在那一天执行</param>
        /// <param name="week">任务在星期几执行</param>
        /// <returns></returns>
        #region private static ITrigger getTriigger(String frequency,ITaskDefinition task, String date, String date, int day, String week)
        private static ITrigger getTriigger(String frequency, ITaskDefinition task, String date, int day, String week)
        {
            ITrigger trigger = null;             //记录定时器

            if (String.IsNullOrEmpty(frequency)) //任务启动频率为空值
            {
                Logger.info(typeof(TaskSchedulerUtils), "task scheduler is empty");
                return(null);
            }

            try
            {
                if (frequency.Equals("weekly"))//每周启动一次
                {
                    //获取周定时器
                    IWeeklyTrigger weekly = task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY) as IWeeklyTrigger;
                    weekly.StartBoundary = date;//设置任务开始时间
                    //week 取值为mon ,tues,wed,thur,fru,sat,sun
                    if (String.IsNullOrEmpty(week) || week.ToLower().Equals("mon"))
                    {
                        //每周一执行
                        weekly.DaysOfWeek = 2;
                    }
                    else if (week.ToLower().Equals("tues"))
                    {
                        //每周二执行
                        weekly.DaysOfWeek = 4;
                    }
                    else if (week.ToLower().Equals("wed"))
                    {
                        //每周三执行
                        weekly.DaysOfWeek = 8;
                    }
                    else if (week.ToLower().Equals("thur"))
                    {
                        //每周四执行
                        weekly.DaysOfWeek = 16;
                    }
                    else if (week.ToLower().Equals("fri"))
                    {
                        //每周五执行
                        weekly.DaysOfWeek = 32;
                    }
                    else if (week.ToLower().Equals("sat"))
                    {
                        //每周六执行
                        weekly.DaysOfWeek = 64;
                    }
                    else
                    {
                        //其他时间,设置为每周日执行
                        weekly.DaysOfWeek = 1;
                    }
                    trigger = weekly;
                }
                else if (frequency.Equals("monthly"))//任务每月执行一次
                {
                    //实例化月定时器
                    IMonthlyTrigger monthly = task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_MONTHLY) as IMonthlyTrigger;
                    //设置任务开始时间
                    monthly.StartBoundary = date;
                    if (day <= 0 || day > 31)//设置的天数超出月份的正常天数范围,则默认每月1号执行任务
                    {
                        monthly.DaysOfMonth = 1;
                    }
                    else
                    {
                        //设置执行任务的日期
                        monthly.DaysOfMonth = (int)Math.Pow(2.0, (day - 1) * 1.0);
                    }
                    trigger = monthly;
                }
                else
                {
                    //获取天定时器
                    IDailyTrigger daily = task.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY) as IDailyTrigger;
                    //设置开始时间
                    daily.StartBoundary = date;
                    trigger             = daily;
                }
            }
            catch (Exception ex)
            {
                Logger.error(typeof(TaskSchedulerUtils), ex);
            }
            return(trigger);
        }
Пример #14
0
        private void AddTaskTrigger(ITaskDefinition iTaskDefinition, ScheduledJobTrigger jobTrigger)
        {
            ITrigger         str;
            string           user;
            TriggerFrequency frequency = jobTrigger.Frequency;

            switch (frequency)
            {
            case TriggerFrequency.Once:
            {
                str = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME);
                ITimeTrigger wTSString = str as ITimeTrigger;
                wTSString.RandomDelay = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                TimeSpan?repetitionInterval = jobTrigger.RepetitionInterval;
                if (repetitionInterval.HasValue)
                {
                    TimeSpan?repetitionDuration = jobTrigger.RepetitionDuration;
                    if (repetitionDuration.HasValue)
                    {
                        TimeSpan?nullable = jobTrigger.RepetitionInterval;
                        wTSString.Repetition.Interval = ScheduledJobWTS.ConvertTimeSpanToWTSString(nullable.Value);
                        TimeSpan?repetitionDuration1 = jobTrigger.RepetitionDuration;
                        if (repetitionDuration1.Value != TimeSpan.MaxValue)
                        {
                            wTSString.Repetition.StopAtDurationEnd = true;
                            TimeSpan?nullable1 = jobTrigger.RepetitionDuration;
                            wTSString.Repetition.Duration = ScheduledJobWTS.ConvertTimeSpanToWTSString(nullable1.Value);
                        }
                        else
                        {
                            wTSString.Repetition.StopAtDurationEnd = false;
                        }
                    }
                }
                str.StartBoundary = ScheduledJobWTS.ConvertDateTimeToString(jobTrigger.At);
                int id = jobTrigger.Id;
                str.Id      = id.ToString(CultureInfo.InvariantCulture);
                str.Enabled = jobTrigger.Enabled;
                return;
            }

            case TriggerFrequency.Daily:
            {
                str = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY);
                IDailyTrigger interval = str as IDailyTrigger;
                interval.RandomDelay  = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                interval.DaysInterval = (short)jobTrigger.Interval;
                str.StartBoundary     = ScheduledJobWTS.ConvertDateTimeToString(jobTrigger.At);
                int num = jobTrigger.Id;
                str.Id      = num.ToString(CultureInfo.InvariantCulture);
                str.Enabled = jobTrigger.Enabled;
                return;
            }

            case TriggerFrequency.Weekly:
            {
                str = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY);
                IWeeklyTrigger mask = str as IWeeklyTrigger;
                mask.RandomDelay   = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                mask.WeeksInterval = (short)jobTrigger.Interval;
                mask.DaysOfWeek    = ScheduledJobWTS.ConvertDaysOfWeekToMask(jobTrigger.DaysOfWeek);
                str.StartBoundary  = ScheduledJobWTS.ConvertDateTimeToString(jobTrigger.At);
                int id1 = jobTrigger.Id;
                str.Id      = id1.ToString(CultureInfo.InvariantCulture);
                str.Enabled = jobTrigger.Enabled;
                return;
            }

            case TriggerFrequency.AtLogon:
            {
                str = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON);
                ILogonTrigger variable  = str as ILogonTrigger;
                ILogonTrigger variable1 = variable;
                if (ScheduledJobTrigger.IsAllUsers(jobTrigger.User))
                {
                    user = null;
                }
                else
                {
                    user = jobTrigger.User;
                }
                variable1.UserId = user;
                variable.Delay   = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                int num1 = jobTrigger.Id;
                str.Id      = num1.ToString(CultureInfo.InvariantCulture);
                str.Enabled = jobTrigger.Enabled;
                return;
            }

            case TriggerFrequency.AtStartup:
            {
                str = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_BOOT);
                IBootTrigger wTSString1 = str as IBootTrigger;
                wTSString1.Delay = ScheduledJobWTS.ConvertTimeSpanToWTSString(jobTrigger.RandomDelay);
                int id2 = jobTrigger.Id;
                str.Id      = id2.ToString(CultureInfo.InvariantCulture);
                str.Enabled = jobTrigger.Enabled;
                return;
            }

            default:
            {
                return;
            }
            }
        }