Advertisement
Codewilly

Execute Scheduled Task and Wait be Done

Oct 21st, 2020
2,558
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.16 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4. using System.Text.RegularExpressions;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ScheduledTask
  8. {
  9.     class Program
  10.     {
  11.         static void Main(string[] args)
  12.         {
  13.             string taskName = "Your Scheduled Task Name";
  14.  
  15.             Process loteWinProcess = new Process
  16.             {
  17.                 StartInfo = new ProcessStartInfo
  18.                 {
  19.                     FileName = "CMD.exe",
  20.                     Arguments = @$"/C SCHTASKS.EXE /RUN /TN ""{taskName}""",
  21.                     UseShellExecute = false,
  22.                     RedirectStandardOutput = true,
  23.                     CreateNoWindow = true
  24.                 }
  25.             };
  26.  
  27.             Console.WriteLine($"Started Task: {taskName}");
  28.  
  29.             loteWinProcess.Start();
  30.             loteWinProcess.WaitForExit();
  31.  
  32.             WaitScheduledTaskBeDone(taskName);
  33.  
  34.             Console.WriteLine("Success!");
  35.             Console.Beep();
  36.         }
  37.  
  38.         public static void WaitScheduledTaskBeDone(string taskName, int delay = 1000)
  39.         {
  40.             string status = GetScheduledTaskStatus(taskName);
  41.  
  42.             while (status != "READY" && status != "PRONTO")
  43.             {
  44.                 status = GetScheduledTaskStatus(taskName);
  45.  
  46.                 Task.Delay(delay).Wait();
  47.             }
  48.         }
  49.  
  50.         public static string GetScheduledTaskStatus(string taskName)
  51.         {
  52.             Process scheduledTaskProcess = new Process
  53.             {
  54.                 StartInfo = new ProcessStartInfo
  55.                 {
  56.                     FileName = "SCHTASKS.exe",
  57.                     Arguments = @$"/Query /TN ""{taskName}"" /FO TABLE /NH",
  58.                     UseShellExecute = false,
  59.                     RedirectStandardOutput = true
  60.                 }
  61.             };
  62.  
  63.             scheduledTaskProcess.Start();
  64.  
  65.             scheduledTaskProcess.WaitForExit();
  66.  
  67.             return Regex.Replace(scheduledTaskProcess.StandardOutput.ReadToEnd().ToUpper(), @"\t|\n|\r", "")
  68.                         .Split(" ", StringSplitOptions.RemoveEmptyEntries)
  69.                         .LastOrDefault();
  70.         }
  71.     }
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement