Dylan Beck
Dylan Beck

Reputation: 197

Creating a function to run according to time of day

Currently working on something in visual C#. What I have now is an application that takes input from a textbox and when they hit the start button the program will run and grab that info. What I want to do with it is check what time they input and compare it to the current time on the computer and run a function when the clock reaches that time. This is something I'll have running for many weeks at a time. Any idea how I could do this? Or maybe the best way to do it? Will provide more info if needed.

This is what it looks like thus far: Current Setup

I'm not sure if I should be using a standard textbox or something else for this. Thanks!

EDIT: OK well, I ended up not creating this program in C# at all. I ended up writing a 1 line batch file that utilized Robocopy (built into Windows) to verify and copy files. Then I used Task Scheduler (also built into Windows) to make sure the batch file is run every day at XX time of day.

Upvotes: 0

Views: 757

Answers (2)

Nino
Nino

Reputation: 7115

if your task should be run at a specific hour and minute (not second), you could write date and time that user entered into xml or database. Then, at the same time, application could check xml/database every minute and if date/time is right, it would execute your method.

Alternatively, you can use System.Timer class and when user enters date and time, calculate milliseconds from current time to entered, and start timer. When time elapses, call your method.

Timer class can take int32.MaxValue as maximal interval which is around 3 and half weeks

here is an example (very basic one) of timer usage

    public Timer MyTimer { get; set; }

    private void button1_Click(object sender, EventArgs e)
    {
        DateTime datetime = DateTime.Parse(textBox1.Text);

        double ms = datetime.Subtract(DateTime.Now).TotalMilliseconds;
        MyTimer = new Timer();
        MyTimer.Interval = (int)ms;

        MyTimer.Tick += T_Tick;
        MyTimer.Start();

    }

    private void T_Tick(object sender, EventArgs e)
    {
        MyTimer.Stop();
        //call your method here
    }

Upvotes: 0

Peter Bons
Peter Bons

Reputation: 29880

You can use a timer as @Equalsk suggests or use Reactive Extensions (it is a NuGet package,see https://www.nuget.org/packages/System.Reactive/) and do something like this:

var dueTime = DateTime.Parse(TextBox1.Text);
Observable.Timer(dueTime).Subscribe(time =>
                {
                    // do something
                });

Instead of a TextBox you should use a DateTimePicker. See https://msdn.microsoft.com/en-us/library/ms229631(v=vs.110).aspx

Upvotes: 1

Related Questions