示例#1
0
 protected override sealed void ExecuteTask()
 {
     using (ScheduledTasks scheduledTasks = new ScheduledTasks())
     {
         ExecuteATTask(scheduledTasks);
     }
 }
示例#2
0
文件: Form1.cs 项目: windrobin/kumpro
 private void bREG_Click(object sender, EventArgs e) {
     ScheduledTasks st = new ScheduledTasks();
     st.DeleteTask(TN);
     Task task = st.CreateTask(TN);
     task.ApplicationName = Path.Combine(Application.StartupPath, "U4ieServer.exe");
     task.Parameters = " \"" + textBox1.Text + "\" \"" + comboBox1.Text + "\" \"" + textBox2.Text + "\" ";
     task.Triggers.Add(new DailyTrigger(10, 0));
     task.Save();
     task.DisplayForEdit();
 }
示例#3
0
文件: Program.cs 项目: comcom/noaartp
        /// <summary>
        /// Verifies whether the scheduled task exists, and if not, creates the scheduled task. See http://stackoverflow.com/a/2490142/130164.
        /// </summary>
        static void verifyScheduledTask()
        {
            //Get a ScheduledTasks object for the local computer.
            var st = new ScheduledTasks();

            // Create a task
            Task t;
            try
            {
                t = st.CreateTask("rtpupdate");
            }
            catch (ArgumentException)
            {
                Console.WriteLine("Scheduled task already set up.");
                return;
            }

            // Fill in the program info
            t.ApplicationName = System.Reflection.Assembly.GetExecutingAssembly().Location; // "chkdsk.exe"
            t.Parameters = ""; // "d: /f"
            t.Comment = "Retrieves RTP data from NOAA for San Diego stations."; // "Checks and fixes errors on D: drive"

            Console.WriteLine(@"Enter username in the form THEDOMAIN\TheUser.");
            var username = Console.ReadLine();
            Console.WriteLine("Enter password.");
            var password = Console.ReadLine();

            // Set the account under which the task should run.
            t.SetAccountInformation(username, password); //t.SetAccountInformation(@"THEDOMAIN\TheUser", "HisPasswd");

            // Declare that the system must have been idle for ten minutes before
            // the task will start
            t.IdleWaitMinutes = 10;

            // Allow the task to run for no more than 2 hours, 30 minutes.
            t.MaxRunTime = new TimeSpan(2, 30, 0);

            // Set priority to only run when system is idle.
            //t.Priority = System.Diagnostics.ProcessPriorityClass.Idle; // this option never worked for me

            // Create a trigger to start the task every Sunday at 6:30 AM.
            t.Triggers.Add(new DailyTrigger(0, 30)); //t.Triggers.Add(new WeeklyTrigger(6, 30, DaysOfTheWeek.Sunday));

            // Save the changes that have been made.
            t.Save();
            // Close the task to release its COM resources.
            t.Close();
            // Dispose the ScheduledTasks to release its COM resources.
            st.Dispose();
        }
示例#4
0
        protected override void ExecuteATTask(ScheduledTasks scheduledTasks)
        {
            bool deleted = false;
            string[] taskNames = scheduledTasks.GetTaskNames();
            foreach (string existingTaskName in taskNames)
            {
                if (TaskName.Equals(existingTaskName))
                {
                    Log(Level.Info, Resources.ATDelJobDeleting, TaskName);
                    scheduledTasks.DeleteTask(TaskName);
                    deleted = true;
                }
            }

            if(!deleted)
            {
                Log(Level.Info, Resources.ATDelJobNotFound, TaskName);
            }
        }
示例#5
0
文件: NForm.cs 项目: windrobin/kumpro
        private void bREG_Click(object sender, EventArgs e) {
            E.SetError(tbUri,null);
            if (tbUri.TextLength == 0) { E.SetError(tbUri, "入力してください"); return; }

            ScheduledTasks st = new ScheduledTasks();
            st.DeleteTask(tbTask.Text);
            Task task = st.CreateTask(tbTask.Text);
            task.ApplicationName = System.Reflection.Assembly.GetExecutingAssembly().Location;
            task.Flags = TaskFlags.SystemRequired;
            task.MaxRunTime = TimeSpan.FromMinutes(30);
            task.MaxRunTimeLimited = true;
            task.Parameters = " \"" + tbUri.Text + "\"";
            task.WorkingDirectory = Application.StartupPath;

            if (rbH6.Checked) {
                DailyTrigger t = new DailyTrigger(9, 0);

                t.DaysInterval = 1;
                t.DurationMinutes = 24 * 60;
                t.IntervalMinutes = 6 * 60;

                task.Triggers.Add(t);
            }
            else if (rbD1.Checked) {
                DailyTrigger t = new DailyTrigger(9, 0);

                t.DaysInterval = 1;

                task.Triggers.Add(t);
            }
            else if (rbD3.Checked) {
                DailyTrigger t = new DailyTrigger(9, 0);

                t.DaysInterval = 3;

                task.Triggers.Add(t);
            }

            task.Save(tbTask.Text);
            task.DisplayForEdit();
        }
示例#6
0
        private void frmMain_Load(object sender, EventArgs e)
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            frmSplash frm    = null;
            bool      splash = ShowSplash();

            if (splash)
            {
                frm         = new frmSplash();
                frm.TopMost = true;
                frm.ShowDialog(this);
            }



            SetupListViewDevices();
            m_Tasks = new ScheduledTasks();

            LoadData();
            LoadTasks();

            if (splash)
            {
                frm.TopMost = false;
                frm.Close();
            }

            if (IsPasswordPrincipalActive())
            {
                if (ShowAskSecurityPolicy())
                {
                    frmAskSecurityPolicy policy = new frmAskSecurityPolicy();
                    DialogResult         result = policy.ShowDialog(this);

                    policy.Close();
                }
            }
        }
示例#7
0
        protected override void ExecuteATTask(ScheduledTasks scheduledTasks)
        {
            ATDelJobTask delJobTask = new ATDelJobTask();
            CopyTo(delJobTask);
            delJobTask.Parent = this;
            delJobTask.TaskName = TaskName;
            delJobTask.Execute();

            Log(Level.Info, Resources.ATAddJobAdding, TaskName);
            using (Task newTask = scheduledTasks.CreateTask(TaskName))
            {
                newTask.ApplicationName = Program.FullName;
                newTask.Comment = Comment;
                if (!string.IsNullOrEmpty(Arguments))
                    newTask.Parameters = Arguments;

                if (Credentials != null)
                {
                    newTask.SetAccountInformation(string.Concat(Credentials.Domain, @"\", Credentials.UserName), Credentials.Password);
                }

                if (WorkingDirectory != null)
                    newTask.WorkingDirectory = WorkingDirectory.FullName;

                newTask.Creator = string.Format(@"[NAntConsole] {0}\{1}", Environment.UserDomainName, Environment.UserName);

                IList<ATTriggerElement> sheduledTriggers = Triggers.GetTriggers();
                foreach (ATTriggerElement trigger in sheduledTriggers)
                {
                    Log(Level.Info, Resources.ATAddJobAddingTrigger, trigger);
                    newTask.Triggers.Add(trigger.CreateTrigger());
                }

                newTask.Save();
            }
        }
示例#8
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            UserAccount Account = new UserAccount();

            // We can'task set up a scheduled task if the user has no password, so test this first:
            if (Account.IsUserPasswordBlank())
            {
                MessageBox.Show(Properties.Resources.ErrorBlankPassword,
                    Properties.Resources.MsgTitle, MessageBoxButtons.OK,
                    MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1,
                    MessageBoxOptions.ServiceNotification);
                return;
            }

            // Ensure the Task Scheduler service is running:
            ServiceController sc = new ServiceController("Schedule");
            try
            {
                if (sc.Status == ServiceControllerStatus.Stopped)
                {
                    const int SixtySecondsAsMilliSeconds = 60 * 1000;
                    TimeSpan timeout = TimeSpan.FromMilliseconds(SixtySecondsAsMilliSeconds);
                    sc.Start();
                    sc.WaitForStatus(ServiceControllerStatus.Running, timeout);
                }
            }
            catch
            {
                MessageBox.Show(Properties.Resources.ErrorSchedulerService,
                    Properties.Resources.MsgTitle, MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation);
                return;
            }

            // Initiate link to Windows Task Scheduler:
            const string TaskNameRoot = "SIL FieldWorks Backup";
            const string TaskNameExtRoot = TaskNameRoot + " by ";
            string TaskName = TaskNameExtRoot + Account.AccountNameAlt;

            // Investigate if there are any backup schedules created by others:
            ScheduledTasks TaskList = new ScheduledTasks();
            string[] TaskNames = TaskList.GetTaskNames();
            string ScheduleOwners = "";
            bool fMeIncluded = false;
            int ctOtherUsersSchedules = 0;
            foreach (string CurrentTaskName in TaskNames)
            {
                if (CurrentTaskName.StartsWith(TaskNameExtRoot))
                {
                    string Schedule = "";
                    Task CurrentTask = TaskList.OpenTask(CurrentTaskName);
                    if (CurrentTask != null)
                    {
                        foreach (Trigger tr in CurrentTask.Triggers)
                        {
                            if (Schedule.Length > 0)
                                Schedule += "; ";
                            Schedule += tr.ToString();
                        }
                        CurrentTask.Close();
                    }
                    string Owner = CurrentTaskName.Substring(TaskNameExtRoot.Length);
                    if (Owner.EndsWith(".job", StringComparison.CurrentCultureIgnoreCase))
                        Owner = Owner.Remove(Owner.Length - 4);
                    if (Owner == Account.AccountNameAlt)
                    {
                        fMeIncluded = true;
                        ScheduleOwners += Properties.Resources.MsgOtherSchedulersMe;
                    }
                    else
                    {
                        ScheduleOwners += Owner;
                        ctOtherUsersSchedules++;
                    }
                    ScheduleOwners += ": " +
                        ((Schedule.Length > 0) ? Schedule :
                        Properties.Resources.MsgScheduleNotAccessible);

                    ScheduleOwners += Environment.NewLine;
                }
            }
            if (ctOtherUsersSchedules > 0)
            {
                string Msg = Properties.Resources.MsgOtherSchedulers + Environment.NewLine
                    + ScheduleOwners + Environment.NewLine
                    + (fMeIncluded? Properties.Resources.MsgOtherSchedulersAndMe :
                    Properties.Resources.MsgOtherSchedulersNotMe)
                    + Environment.NewLine + Properties.Resources.MsgOtherSchedulersAddendum;
                if (MessageBox.Show(Msg, Properties.Resources.MsgTitle,
                    MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation)
                    == DialogResult.Cancel)
                {
                    return;
                }
            }

            // Retrieve the current Backup task, if there is one:
            bool fPreExistingTask = true;
            Task task = TaskList.OpenTask(TaskName);

            // If there isn'task one already, make a new one:
            if (task == null)
            {
                fPreExistingTask = false;
                task = TaskList.CreateTask(TaskName);

                if (task == null)
                {
                    MessageBox.Show(Properties.Resources.ErrorNoTask,
                        Properties.Resources.ErrorMsgTitle, MessageBoxButtons.OK,
                        MessageBoxIcon.Stop);
                    return;
                }

                // Set the program to run on the schedule by looking up the FW location:
                string ScriptPath = null;
                RegistryKey rKey = Registry.LocalMachine.OpenSubKey(FwHive);
                if (rKey != null)
                {
                    System.Object regObj = rKey.GetValue(FwCodeDir);
                    if (regObj != null)
                    {
                        string FwFolder = regObj.ToString();
                        if (!FwFolder.EndsWith(@"\"))
                            FwFolder += @"\";
                        ScriptPath = FwFolder + FwBackupScript;
                    }
                }
                if (ScriptPath == null)
                {
                    MessageBox.Show(Properties.Resources.ErrorNoScript,
                        Properties.Resources.ErrorMsgTitle, MessageBoxButtons.OK,
                        MessageBoxIcon.Error);
                    return;
                }
                // On 64-bit machines, we have to force the scheduled script to run with the 32-bit // version of the script engine, otherwise it fails to load the 32-bit COM class // in the script:
                if (Is64Bit())
                {
                    // Create the path to the 32-bit script engine:
                    task.ApplicationName = Environment.GetEnvironmentVariable("WINDIR") + @"\SysWOW64\wscript.exe";
                    // put the path to the script in as the parameter to the script engine:
                    task.Parameters = "\"" + ScriptPath + "\"";
                }
                else
                {
                    task.ApplicationName = ScriptPath;
                    task.Parameters = "";
                }
                task.Comment = "Created automatically by FieldWorks Backup system.";

                // Give it an arbitrary weekday run at 5 in the afternoon:
                task.Triggers.Add(new WeeklyTrigger(17, 0, DaysOfTheWeek.Monday |
                    DaysOfTheWeek.Tuesday | DaysOfTheWeek.Wednesday | DaysOfTheWeek.Thursday |
                    DaysOfTheWeek.Friday));
            }

            // Display the Windows Task Scheduler schedule page for our task:
            bool fDisplaySchedule = true;
            while (fDisplaySchedule)
            {
                if (task.DisplayPropertySheet(Task.PropPages.Schedule))
                {
                    // User pressed OK on Schedule page.
                    DialogResult DlgResult;
                    bool fPasswordCorrect = false;
                    do
                    {
                        // User must give their Windows logon password in order to use schedule:
                        BackupSchedulePasswordDlg PwdDlg = new BackupSchedulePasswordDlg();
                        DlgResult = PwdDlg.ShowDialog();
                        SecureString Password = PwdDlg.Password;
                        PwdDlg.Dispose();

                        if (DlgResult == DialogResult.OK)
                        {
                            try
                            {
                                // Test if the password the user gave is correct:
                                fPasswordCorrect = Account.IsPasswordCorrect(Password);
                                if (fPasswordCorrect)
                                {
                                    // Configure the scheduled task with the user account details:
                                    task.SetAccountInformation(Account.AccountName, Password);
                                    task.Save();
                                    fDisplaySchedule = false;
                                }
                            }
                            catch (System.Exception e)
                            {
                                if (e.Message == "Password error")
                                    DlgResult = DialogResult.Cancel;
                            }
                        }
                    } while (DlgResult == DialogResult.OK && !fPasswordCorrect);
                }
                else // User pressed cancel on Task Scheduler dialog
                {
                    if (fPreExistingTask)
                    {
                        // Give user the option to delete the pre-existing shceduled backup.

                        // Make a string listing the scheduled backup time(s):
                        string Schedule = Properties.Resources.MsgCurrentSchedule;
                        Schedule += Environment.NewLine;
                        foreach (Trigger tr in task.Triggers)
                            Schedule += tr.ToString() + Environment.NewLine;
                        Schedule += Environment.NewLine;
                        if (MessageBox.Show(
                            Schedule + Properties.Resources.MsgDeleteExistingTask,
                            Properties.Resources.MsgTitle, MessageBoxButtons.YesNo,
                            MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
                            == DialogResult.Yes)
                        {
                            task.Close();
                            task = null;
                            TaskList.DeleteTask(TaskName);
                        }
                    }
                    fDisplaySchedule = false;
                }
            } // End while fDisplaySchedule
            if (task != null)
                task.Close();
        }
示例#9
0
 protected abstract void ExecuteATTask(ScheduledTasks scheduledTasks);
示例#10
0
        private void frmMain_Load(object sender, EventArgs e)
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            frmSplash frm = null;
            bool splash = ShowSplash();

            if (splash)
            {
                frm = new frmSplash();
                frm.TopMost = true;
                frm.ShowDialog(this);
            }

            SetupListViewDevices();
            m_Tasks = new ScheduledTasks();

            LoadData();
            LoadTasks();

            if (splash)
            {
                frm.TopMost = false;
                frm.Close();
            }

            if (IsPasswordPrincipalActive())
            {
                if (ShowAskSecurityPolicy())
                {
                    frmAskSecurityPolicy policy = new frmAskSecurityPolicy();
                    DialogResult result = policy.ShowDialog(this);

                    policy.Close();
                }
            }
        }
示例#11
0
 internal TaskList(string computer)
 {
     st = new ScheduledTasks(computer);
 }
示例#12
0
 /// <summary>
 /// Constructors - marked internal so you have to create using Scheduler class.
 /// </summary>
 internal TaskList()
 {
     st = new ScheduledTasks();
 }
示例#13
0
 /// <summary>
 /// Internal constructor - Only accessable through <see cref="IEnumerable.GetEnumerator()"/>
 /// </summary>
 /// <param name="st">ScheduledTasks object</param>
 internal Enumerator(ScheduledTasks st)
 {
     outer = st;
     nameTask = st.GetTaskNames();
     Reset();
 }
示例#14
0
 /// <summary>
 /// Internal constructor - Only accessable through <see cref="IEnumerable.GetEnumerator()"/>
 /// </summary>
 /// <param name="st">ScheduledTasks object</param>
 internal Enumerator(ScheduledTasks st)
 {
     outer    = st;
     nameTask = st.GetTaskNames();
     Reset();
 }
示例#15
0
 internal TaskList(string computer)
 {
     st = new ScheduledTasks(computer);
 }
示例#16
0
 /// <summary>
 /// Constructors - marked internal so you have to create using Scheduler class.
 /// </summary>
 internal TaskList()
 {
     st = new ScheduledTasks();
 }