Question

I was wondering if the following code snippet is the correct way:

Logger.Debug("Check file exists for corresponding path: {0}.", filePath);
var timeDeadline = DateTime.Today + Settings.Default.FileDeadline; //Timespan type
while (!File.Exists(filePath))
{
    if (DateTime.Now > timeDeadline)
        Logger.Error("The file is not available: {0}.", filePath);
    Logger.Info("The file is not yet available. Waiting for 1 hour...");
    Thread.Sleep(TimeSpan.FromHours(1));
}

The purpose of this code is to schedule it early in the morning with the Windows Task Scheduler to load a file that comes normally around 9:00 but can have delays of hours and at the end is needed before 14:30 (FileDeadline) when I will report the missing file as an error if still missing.

I could also throw an exception very hour and allow windows task to restart the process every hour but I thought better to let C# have all the control of the process. The disadvantage is the thread sleeping one hour and having a scheduled task running hours. I don't mind if the resources used are negligible but I though some more experienced programmers might have a more elegant solution.

Was it helpful?

Solution

Thread.Sleep is a bad idea, use a timer (System.Timers) to do the job. See http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx for info on Timer class

OTHER TIPS

If you want to schedule something my suggestion is to use something like Quartz.Net which is far superior to Windows Tasks in terms of flexibility and long term maintenance.

An alternative to polling is to actually listen to the events that occur when a file is written in the file system. In the .Net framework there is the FileSystemWatcher class that you can use to listen to file system events on a certain directory. However, the FileSystemWatcher is not 100% fool proof so a combination of the two methods is usually the best solution.

You could also use a FileSystemWatcher, although I have heard that it can be unreliable http://msdn.microsoft.com/en-gb/library/system.io.filesystemwatcher.aspx

Juts a warn in case:

If the file you're waiting for commes trough a FTP(or something that create a "growing file"), it can happen that you get an event telling your file is there but it's not complete. And also the method File.exists will also return true. Even if your file is partial.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top