Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# create a timer loop which runs code every 30 minutes?

I would like to input an autosave feature in my C# program which will run a line of code at the end of the countdown, then restart the countdown. It will run my SaveFile(); function.

I would like this timer to be started when the user first saves/opens the document, and have it disabled if they open a new document.

like image 886
Toby Avatar asked Apr 26 '13 16:04

Toby


3 Answers

You can use the Elapsed event on the System.Timers Timer.

Timer timer = new Timer(30 * 60 * 1000);
timer.Elapsed += OnTick; // Which can also be written as += new ElapsedEventHandler(OnTick);


private void OnTick(object source, ElapsedEventArgs e)
{ 
    //Save logic
}

And don't forget to call timer.Start() when you need it.

like image 133
Pierre-Luc Pineault Avatar answered Oct 17 '22 17:10

Pierre-Luc Pineault


You can also use DispatchTimer. Here's a snippet that plays one of five different videos every 5 minutes.

        DispatcherTimer mediaTimer = new DispatcherTimer();
        mediaTimer.Interval = TimeSpan.FromMinutes(5);
        mediaTimer.Tick += new EventHandler(mediaTimer_Tick);
        mediaTimer.Start();

    void mediaTimer_Tick(object sender, EventArgs e)
    {
        nextMovie();
    }

    public void nextMovie()
    {
        if (mediaIndex >= 5)
            mediaIndex = 0;

        switch (mediaIndex)
        {
            case 0:
                mediaElement1.Source = new Uri(videoFileName1, UriKind.Absolute);
                break;
            case 1:
                mediaElement1.Source = new Uri(videoFileName2, UriKind.Absolute);
                break;
            case 2:
                mediaElement1.Source = new Uri(videoFileName3, UriKind.Absolute);
                break;
            case 3:
                mediaElement1.Source = new Uri(videoFileName4, UriKind.Absolute);
                break;
            case 4:
                mediaElement1.Source = new Uri(videoFileName5, UriKind.Absolute);
                break;
            default:
                mediaElement1.Source = new Uri(videoFileName1, UriKind.Absolute);
                break;

        }

        mediaElement1.Visibility = System.Windows.Visibility.Visible;
        mediaIndex++;
        mediaElement1.Play();
    }
like image 24
Geoff Murtaugh Avatar answered Oct 17 '22 16:10

Geoff Murtaugh


You can use System.Timers.Timer. It also has Stop and Start methods so you can do whatever you want.

System.Timers.Timer myTimer = new Timer(30 * 60 * 1000);
myTimer.Start();
myTimer.Elapsed += new ElapsedEventHandler(myTimer_Elapsed);


void myTimer_Elapsed(object sender, ElapsedEventArgs e)
{
    //your code
}
like image 1
Hossein Narimani Rad Avatar answered Oct 17 '22 16:10

Hossein Narimani Rad