简体   繁体   中英

how to call a method after every X minute for certain amount of time

I have 2 methods. 1st method starts an .exe and 2nd method looks for output file created by that .exe.

  1. program should start looking for output X minutes(defined in app.config) after .exe is called.

  2. it should call the method to look for an output file, after certain frequency(defined in app.config) it should invoke itself, look for an output file if found return success break out of loop go to next line if false go to sleep.

  3. repeat step 2 up until Y minutes(defined in app.config) are reached since the .exe is called. if it exceeds then stop return failure and go to next statement.

I can use datetime.now to get time at which .exe is started but cannot figure out how to add X and Y minutes to it and how to use those time limits.

Here is my code so far:

//Running the process .exe
DV.runprocess();
// check output file
String checkOutputFrequency=System.Configuration.ConfigurationManager.AppSettings["CheckOutputFrequency"].ToString();
decimal outfrequencyVal = (!string.IsNullOrEmpty(checkOutputFrequency)) ? Decimal.Parse(checkOutputFrequency) : 1;
bool FileFound = false;

while (true)
{
      FileFound = DV.checkOutputFile();

      if (FileFound == true) 
          break;

      System.Threading.Thread.Sleep(Convert.ToInt32(outfrequencyVal * 60 * 1000));
}

Create a new thread and pass in start time. Sleep for X minutes then use your loop codes. For each loop, check if start time plus Y minutes is passed

while (DateTime.Now < startTime.AddMinutes(Y)) {
    //your codes...
}

Another way is async-await

public async Task RunAndListen()
{
    DV.runprocess();

    string checkOutputFrequency = 
        System.Configuration.ConfigurationManager.AppSettings["CheckOutputFrequency"].ToString();

    decimal outfrequencyVal;
    If (Decimal.TryParse(checkOutputFrequency, out outfrequencyVal) == false)
    {
        outfrequencyVal = 1;
    }

    var delayInMilliseconds = outfrequencyVal * 60 * 1000;

    bool FileFound = DV.checkOutputFile();
    while (FileFound == false)
    {
        await Task.Delay(delayInMilliseconds);
        FileFound = DV.checkOutputFile();
    }    
}

Line await Task.Delay(delayInMilliseconds); will effectively release current thread back to ThreadPool and continue executing next line after given time have elapsed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM