Search code examples
c#timer

How would I run a script every 30 seconds?


How would I have my ftp script run every 10 or 30 seconds?

ftp script:

FtpWebRequest makedir = (FtpWebRequest)WebRequest.Create("ftp://xxx.xxx.xxx.xxx/" + System.Environment.MachineName + "___" + System.Environment.UserName + @"/");
makedir.Method = WebRequestMethods.Ftp.MakeDirectory;
makedir.Credentials = new NetworkCredential("usr", @"passwd");
FtpWebResponse makedirStream = (FtpWebResponse)makedir.GetResponse();
makedirStream.Close();

I was reading about using sleep on a thread and also about using a timer.. but I cant figure out how to use either.. The thing is that it also needs to rerun every 30 seconds not just once.


Solution

  • Put your code in a method, for example named RunFtp() & then use a Timer like this:

    var t = new System.Threading.Timer(
        callback: o => RunFtp(), 
        state: null, 
        dueTime: 0,      // run now
        period: 30000);  // milliseconds
    

    There are many different types of timer in .NET, see the green panel in the remarks in the link above for a list.

    Or use Windows Task Scheduler to schedule and run the application repeatedly.

    Or use Task.Delay like this...

    while (true)
    {
        RunFtp();
        System.Threading.Task.Delay(30000).Wait();
    }
    

    ...to make your code to pause for 30 seconds between executions, but you also need to add the execution time of your code each time, so that it will start running every 30 seconds accurately.

    You may also want to consider running this with async/await if you want to avoid blocking.