How to run code daily at specific time in C#

When you want to make some delay in running code you can use Task.Delay(TimeSpan interval) method . This method is similar to Thread.Sleep, but it is nicer. The argument of the method represent TimeSpan type. For example if you want to wait 5 second you can call the following code:

Task.Delay(TimeSpan.FromSeconds(5));

Or you want to wait 2 hours:


Task.Delay(TimeSpan.FromHourss(2));

You can easily use Task.Delay to run some code at certain time. For example you want to run some method every day at 1:00:00 AM. To implement this example you can use Task.Delay method on the following way:
First Convert the time in to DateTime type. Make diference between now and the time you want to run the code. Call Delay method with TimeSpan of previous time interval. The following code solve this problem:

class Program
{
static void Main(string[] args)
{
//Time when method needs to be called
var DailyTime = "01:00:00";
var timeParts = DailyTime.Split(new char[1] { ':' });

var dateNow = DateTime.Now;
var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day,
int.Parse(timeParts[0]), int.Parse(timeParts[1]), int.Parse(timeParts[2]));
TimeSpan ts;
if (date > dateNow)
ts = date - dateNow;
else
{
date = date.AddDays(1);
ts = date - dateNow;
}

//waits certan time and run the code
Task.Delay(ts).ContinueWith((x)=> SomeMethod());

Console.Read();
}

static void SomeMethod()
{
Console.WriteLine("Method is called.");
}
}

If you want that code to run every day, just put it in while loop.

Happy programming.


Posted May 04 2014, 08:29 AM by Bahrudin
Filed under: ,

Comments

Manas wrote re: How to run code daily at specific time in C#
on 03-12-2016 13:51

Hi Bahrudin,

Nice code snippet. But I have one doubt as per your comment "If you want that code to run every day, just put it in while loop.", can you tell me what logic I will implement. It would be better if you can provide demo code snippet.

Regards,

Manas

Vishal wrote re: How to run code daily at specific time in C#
on 03-21-2016 10:00

Check this timer thread. Better way to handle the timely managed tasks.

msdn.microsoft.com/.../swx5easy.aspx

or refer to quartz.net

Thanks

sameera wrote re: How to run code daily at specific time in C#
on 02-28-2017 12:25

how to put a while loop to make it happen every day

developers.de is a .Net Community Blog powered by daenet GmbH.