How to run code daily at specific time in C#


Update: Please see my Updated post about this subject: How to run code daily at specific time in C# part 2

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.FromHours(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.

Update: The complete sample can be similar to the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DailyTaskDemo
{
class Program
{
static void Main(string[] args)
{
//Time when method needs to be called
var DailyTime = “22:37:00″;
var timeParts = DailyTime.Split(new char[1] { ‘:’ });

while(true)
{

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).Wait();
SomeMethod();

}

Console.Read();
}

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

Happy programming.

About Bahrudin Hrnjica

PhD in Mechanical Engineering, Microsoft MVP for .NET. Likes .NET, Math, Mechanical Engineering, Evolutionary Algorithms, Blogging.

Posted on 30/01/2014, in .NET, C# and tagged , , . Bookmark the permalink. 16 Comments.

  1. How it can be done in .net 3.5 or 4.0

  2. Harry Nakken

    When i put the Task in a Loop, a OutOfMemory error occurs ?

    How can i wait till the Task is ended ?

  3. Hi,

    Could you explain me how to run code daily? Thanks :)

  4. The complete sample can look like:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace DailyTaskDemo
    {
    class Program
    {
    static void Main(string[] args)
    {
    //Time when method needs to be called
    var DailyTime = “22:37:00”;
    var timeParts = DailyTime.Split(new char[1] { ‘:’ });

    while(true)
    {

    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).Wait();
    SomeMethod();

    }

    Console.Read();
    }

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

    All you need to define is DailyTime variable to specify right time.It can be also defined from configuration file, or throught some dialog so the user can ener time value at run time.

  5. Lior Derei

    i have 2 variables for hour and minute, how do i use it in delay? if i dont want to enter full date?

    Cheers,
    Lior

    • Sample Demo shown in above comment exactly does what you want.
      In var date = new DateTime line of the code, you can specify your vars which hold hour and minute.

  6. ashutosh tripathi

    i am using your code in my project, but it is not working. I am making a website in which i need to automatically call some method at 23:59 and update database. please help.

  7. How can I have this run everyday at a certain time so then I can just have it run on autopilot.

  8. Can I use your code to acheive a feature where a user posts something and specify a time to be shown to other users on the website at that certain time in asp.net with MS SQL Server. In case of MySql it can easily be achieved using scheduled events.http://www.sitepoint.com/how-to-create-mysql-events/

  1. Pingback: how to run code with interval?(C# .net)

  2. Pingback: How to run code daily at specific time in C# Part 2 | Bahrudin Hrnjica Blog

  3. Pingback: How to run code daily at specific time in C# Part 2 - C# & .NET technologies - developers.de

  4. Pingback: 8 February, 2015 00:32 | What I learned

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s