Programmatically creating scheduled task in Windows using C#

This code is about a fairly simple feature that I believe most software engineers encounter in their projects. I, too, have encountered similar situations on many occasions. Previously, I used Window Service to achieve the features, which worked flawlessly. However, in this article, I will use the same method to accomplish the same goal using Window Scheduler.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;

namespace ScheduleDemo_CS
{
    class Program
    {
        public static readonly string Constans = "SCHTASKS.exe";
        static void Main(string[] args)
        {
            CreateScheduleTask("MINUTE", 1, "aspdotnetcodebook", @"C:\Windows\System32\notepad.exe");
        }

        public static bool CreateProcess(string strProcessName, string strCommandLineParams)
        {
            // set process parameters and invoke the process
            ProcessStartInfo processInfo = new ProcessStartInfo();
            processInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            processInfo.Arguments = strCommandLineParams;
            processInfo.FileName = strProcessName;
            Process process = Process.Start(processInfo);
            process.WaitForExit();
            if (0 != process.ExitCode)
                return false;
            return true;
        }
        public static bool CreateScheduleTask(string strScheduleType, int intTimeInterval, string strTaskName, string strProgramPath)
        {
            StringBuilder commandLineParams = new StringBuilder();
            commandLineParams.AppendFormat("/Create /RU SYSTEM /SC {0} /MO {1} /TN {2} /TR \"\\\"{3}\\\"", strScheduleType.ToUpper(), intTimeInterval, strTaskName, strProgramPath);
            return CreateProcess(Constans, commandLineParams.ToString());
        }
    }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru