user1202434
user1202434

Reputation: 2273

Start a process after a certain time interval in C#?

I have a c# wpf application where in the main() method, I check for a certain condition and if it is true, I run a different process, however, I need to start the process after a certain timeout. So, for eg:

override OnStartUp()

    {
           if(condition == true)
           {
                ProcessStartInfo p = new ProcessStartInfo("filePath");
                p.Start(); // This should wait for like say 5 seconds and then start.
                  return;   // This will exit the current program.
            }
    }

I could use Thread.Sleep() but that will cause the current program to sleep as well. So, in other words, I want the current program to terminate immediately and then new process to start after 5 seconds.

Thanks!

Is this possible?

Upvotes: 4

Views: 2306

Answers (5)

NiladriBose
NiladriBose

Reputation: 1905

I can recomend the very powerful

http://quartznet.sourceforge.net/

For all your scheduling needs.

Upvotes: 0

user629926
user629926

Reputation: 1940

You can use Task Scheduler api and setup one time task that will start app after next 5 seconds.Nice managed wrraper: taskscheduler.codeplex.com

Upvotes: 1

Andreas Rehm
Andreas Rehm

Reputation: 2232

You need to create a new Thread. In this thread you can use Thread.Sleep without blocking your program.

public class MyThread
{
   public static void DoIt()
   {
      Thread.Sleep(100);
      // DO what you need here
   }
}
override OnStartUp()
{
    if(condition == true)
    {
       ThreadStart myThread = new MyThread(wt.DoIt);
       Thread myThread = new Thread(myThread);
       myThread.Start();
    }
}

Upvotes: 0

Exulted
Exulted

Reputation: 373

What if the first process creates a third program. The first program exits immediately, whilst the third one will simply sleep for 5 seconds and then will start your second program.

Upvotes: 4

Ben Voigt
Ben Voigt

Reputation: 283614

You've got a few options:

  1. Modify the process being launched and put the delay there. You can even wait for "the parent has ended" instead of a fixed time.
  2. Windows built-in Scheduled Tasks
  3. A batch file that uses the sleep command and then runs the program

Upvotes: 3

Related Questions