Click here to Skip to main content
15,116,654 members
Articles / Programming Languages / C#
Article
Posted 13 Oct 2014

Tagged as

Stats

83.1K views
27 bookmarked

How to Run Code Daily at a Specific Time in C#: Part 2

Rate me:
Please Sign up or sign in to vote.
4.31/5 (16 votes)
7 Jan 2015CPOL1 min read
How to run code daily at a specific time in C#

dailyruncode

Few months ago, I wrote a blog post about how to run code daily at a specific time. I didn't know that the post will be the most viewed post on my blog. Also, there were several questions how to implement the complete example. So today, I have decided to write another post, and extend my previous post in order to answer these questions as well as to generalize this subject into a cool demo called Scheduler DEMO.

The post is presenting simple Windows Forms application which calls a method for every minute, day, week, month or year. Also, the demo shows how to cancel the scheduler at any time.

The picture above shows a simple Windows Forms application with two numeric controls in which you can set starting hour and minute for the scheduler. Next, there is a button Start to activate timer for running code, as well as Cancel button to cancel the scheduler. When the time comes, the application writes the message on the Scheduler Log.

Implementation of the Scheduler

Scheduler is started by clicking the Start button which is implemented with the following code:

C#
/// <summary>
/// Setting up time for running the code
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void startBtn_Click(object sender, EventArgs e)
{
    //retrieve hour and minute from the form
    int hour = (int)numHours.Value;
    int minutes = (int)numMins.Value;

    //create next date which we need in order to run the code
    var dateNow = DateTime.Now;
    var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, hour, minutes, 0);

    listBox1.Items.Add("**********Scheduler has been started!*****");

    //get nex date the code need to run
    var nextDateValue=getNextDate(date,getScheduler());

    runCodeAt(nextDateValue, getScheduler());
}

When the time is defined, then the runCodeAt method is called which implementation can be like the following:

C#
/// <summary>
/// Determine the timeSpan Delay must wait before running the code
/// </summary>
/// <param name="date"></param>
/// <param name="scheduler"></param>
private void runCodeAt(DateTime date,Scheduler scheduler )
{
    m_ctSource = new CancellationTokenSource();

    var dateNow = DateTime.Now;
    TimeSpan ts;
    if (date > dateNow)
        ts = date - dateNow;
    else
    {
        date = getNextDate(date, scheduler);
        ts = date - dateNow;
    }

    //enable the progressbar
    prepareControlForStart();

    //waits for a certain time and runs the code, 
    //in the mean time, you can cancel the task at any time
    Task.Delay(ts).ContinueWith((x) =>
        {
            //run the code at the time
                methodToCall(date);

                //setup call next day
                runCodeAt(getNextDate(date, scheduler), scheduler);

        },m_ctSource.Token);
}

The method above creates the cancelationToken needed for cancel the scheduler, calculate timeSpan – total waiting time, then when the time comes, call the method methodToCall and calculate the next time for running the scheduler.

This demo also shows how to wait for a certain amount of time without blocking the UI thread.

The full demo code can be found on OneDrive.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Bahrudin Hrnjica
Software Developer (Senior)
Bosnia and Herzegovina Bosnia and Herzegovina
Bahrudin Hrnjica holds a Ph.D. degree in Technical Science/Engineering from University in Bihać.
Besides teaching at University, he is in the software industry for more than two decades, focusing on development technologies e.g. .NET, Visual Studio, Desktop/Web/Cloud solutions.

He works on the development and application of different ML algorithms. In the development of ML-oriented solutions and modeling, he has more than 10 years of experience. His field of interest is also the development of predictive models with the ML.NET and Keras, but also actively develop two ML-based .NET open source projects: GPdotNET-genetic programming tool and ANNdotNET - deep learning tool on .NET platform. He works in multidisciplinary teams with the mission of optimizing and selecting the ML algorithms to build ML models.

He is the author of several books, and many online articles, writes a blog at http://bhrnjica.net, regularly holds lectures at local and regional conferences, User groups and Code Camp gatherings, and is also the founder of the Bihac Developer Meetup Group. Microsoft recognizes his work and awarded him with the prestigious Microsoft MVP title for the first time in 2011, which he still holds today.

Comments and Discussions

 
Questioncode Pin
Member 1365572018-Feb-19 20:51
MemberMember 1365572018-Feb-19 20:51 
QuestionBug in calculating when to run Pin
Member 1365100719-Feb-18 15:52
MemberMember 1365100719-Feb-18 15:52 
AnswerRe: Bug in calculating when to run Pin
Bahrudin Hrnjica19-Jun-18 8:35
professionalBahrudin Hrnjica19-Jun-18 8:35 
Questioncode Pin
Cool Smith14-Feb-18 4:01
MemberCool Smith14-Feb-18 4:01 
AnswerRe: code Pin
Bahrudin Hrnjica19-Jun-18 8:33
professionalBahrudin Hrnjica19-Jun-18 8:33 
the source code is placed on my one-drive account, and the link is shown at the end of the article. But I can post it here: Microsoft OneDrive - Access files anywhere. Create docs with free Office Online.[^]
BugBug ? Pin
Mikisz 1711-Oct-17 8:36
MemberMikisz 1711-Oct-17 8:36 
GeneralRe: Bug ? Pin
Bahrudin Hrnjica19-Jun-18 8:28
professionalBahrudin Hrnjica19-Jun-18 8:28 
Suggestioncrontab Pin
BManfred8-Jan-15 3:27
MemberBManfred8-Jan-15 3:27 
GeneralOther tools Pin
goodEinstein20-Oct-14 2:43
MembergoodEinstein20-Oct-14 2:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.