7

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.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Toby
  • 377
  • 1
  • 10
  • 23
  • A timer would take to many resources, you should take a `BackgroundWorker` or async in .NET 4.5. – Stefan Over Apr 26 '13 at 16:51
  • what do you find confusing about the tutorials? – proggrock Apr 26 '13 at 16:52
  • Just in general I can't understand how to make it work for me. How do you work with Background workers? – Toby Apr 26 '13 at 16:59
  • @Herd: How would you use a `BackgroundWorker` as a timer? His code needs to run on an interval which makes perfect sense to user a timer. But as for saving the file, sure, he can put it in a different thread to prevent freezing the UI. – Arian Motamedi Apr 26 '13 at 17:00
  • @Toby: If you're using .NET 4.0 or 4.5, then it's so much easier to use a `Task`. – Arian Motamedi Apr 26 '13 at 17:01
  • @programmer93: I'm getting slightly confused here... Sorry, I've only recently started programming as part of my college course, so could you perhaps explain things in simple terms for me? Thanks :) – Toby Apr 26 '13 at 17:02
  • @programmer93: I'm using .NET 4.0 – Toby Apr 26 '13 at 17:03
  • @programmer93 e.g. like [this](http://www.codeproject.com/Questions/233329/Timer-inside-Backgroundworker-in-Csharp-net). – Stefan Over Apr 26 '13 at 17:07
  • @Toby see the link above. In my opinion it's better practice to use an other thread that sleeps and takes less memory than a timer. – Stefan Over Apr 26 '13 at 17:08
  • Alright. I'll try and figure it out using that source. Thanks for the link. – Toby Apr 26 '13 at 17:14
  • @Toby The only time you use a `BackgroundWorker` is when you want to have an async operation AND you want to be notified about the status of that operation as it makes a progress. For example, when you want to download a file and want to have a progress bar that gets updated based on the number of bytes downloaded. It seems to me in your case it makes sense to just put your `Save` method in a `Task` (which is really two lines of code) and have it executed on a different thread. Take a look at [this](http://stackoverflow.com/questions/1506838/backgroundworker-vs-background-thread). – Arian Motamedi Apr 26 '13 at 17:30

4 Answers4

10

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.

Pierre-Luc Pineault
  • 8,993
  • 6
  • 40
  • 55
  • timer.Enabled = true is required. – lsalamon Jun 30 '14 at 20:41
  • 1
    @Isalamon Actually if you start the timer (`timer.Start();`) you don't need to set `Enabled` to true explicitly. And I just saw I've written the whole `new ElapsedEventHandler` declaration which is useless, `timer.Elapsed += OnTick;` is much cleaner. – Pierre-Luc Pineault Jun 30 '14 at 22:41
2

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();
    }
1

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
}
Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
-8

Opening New Window

 FrmCupsToOunces MyNewForm = new FrmCupsToOunces();
        MyNewForm.Show();

Making Array

const int QUARTERS = 4;
        const int DIVISIONS = 3;

        double[,] stats = new double[DIVISIONS, QUARTERS];

Making Password Check

int InNumTry = 0;
    private void BtnGo_Click_1(object sender, EventArgs e)
    {
        string password;
        password = TxtIn.Text;

            switch (password)
            {
                case " ": MessageBox.Show("Passowrd is empty.");
                    break;

                case "MIKE": MessageBox.Show("Password is OK!");
                    FrmBOO newForm = new FrmBOO();
                    newForm.Show();
                    break;

                default:
                    InNumTry++;
                    MessageBox.Show("Invalid Passwrod, try again!");
                    TxtIn.Text = "";
                    TxtIn.Focus();
                    break;
            }

Check Length

LblLength.Text = TxtInput.Text.Length.ToString();

Make To Upper

LblUpper.Text = TxtInput.Text.ToUpper();

Make To Lower

LblLower.Text = TxtInput.Text.ToLower();

Last Right Three

LblRight.Text = TxtInput.Text.Substring(TxtInput.Text.Length - 3);

Show Middle Characters

LblSubscript.Text = TxtInput.Text.Substring(1, 3);

ASCII

private void btnascii_Click(object sender, EventArgs e)
    {
        string assqui;
        int num;
        num = Convert.ToInt32(txtinput.Text);
        assqui = char.ConvertFromUtf32(num);
        lblascii.Text = assqui.ToString();
    }

CONVERT A CHARACTER TO ASCII

        string assqui;
        int num;
        num = Convert.ToInt32(textBox1.Text);
        assqui= char.ConvertFromUtf32(num);
        lblout.Text = assqui.ToString();

Show Difference

 string name;
        name = txtinput.Text;
        foreach (char letter in name)
        {
            MessageBox.Show(letter.ToString());
        }

Get File

private void BtnGetFile_Click(object sender, EventArgs e)
    {
        string Line;
        int count = 0;

        try
        {
            StreamReader ReadFile;

            StringFileName = Interaction.InputBox(" Please Enter Your Desired File Name \n You do not need to place the '.txt' at the end of the file name.") + ".txt";

            ReadFile = File.OpenText(StringFileName);

            LbSongs.Items.Clear();

            while (!ReadFile.EndOfStream)
            {
                Line = ReadFile.ReadLine();
                string[] words = Line.Split(',');

                ListSongs[count].NameOfSong = words[0];
                ListSongs[count].NameOfArtist = words[1];
                ListSongs[count].NameOfFile = words[2];
                ListSongs[count].ThisWeekRank = words[3];
                ListSongs[count].MostWeekRank = words[4];
                ListSongs[count].LastWeekRank = words[5];

                LbSongs.Items.Add(ListSongs[count].NameOfSong);

                count++;
            }

            LbSongs.SelectedIndex = 0;
            Show();
            ReadFile.Close();
        }
        catch
        {
            MessageBox.Show("The file you are trying to access either, can not be found or opened");
        }

    }
    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void infoToolStripMenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show("The Program was created by Konrad Lazarek.\n\nOn April 16st, 2014.\n\nVersion: 00:03:48:59",
        "Info On This Program",
        MessageBoxButtons.OK,
        MessageBoxIcon.Information,
        MessageBoxDefaultButton.Button1);
    }

    private void BTF(int index)
    {
        switch (ListSongs[index].NameOfSong)
        {
            case "Happy":
                HidePictures();
                PicHappy.Visible = true;
                break;
            case "All Of Me":
                HidePictures();
                PicAllOfMe.Visible = true;
                break;
            case "Dark Horse":
                HidePictures();
                PicDarkHorse.Visible = true;
                break;
            case "Talk Dirty":
                HidePictures();
                PicTalkDirty.Visible = true;
                break;
            case "Let It Go":
                HidePictures();
                PicLetItGo.Visible = true;
                break;
            case "Pompeii":
                HidePictures();
                PicPompeii.Visible = true;
                break;
            case "Team":
                HidePictures();
                PicTeam.Visible = true;
                break;
            case "Counting Stars":
                HidePictures();
                PicCountingStars.Visible = true;
                break;
            case "The Man":
                HidePictures();
                PicTheMan.Visible = true;
                break;
            case "Turn Down For What":
                HidePictures();
                PicTurnDownForWhat.Visible = true;
                break;
        }
    }

private void LbSongs_SelectedIndexChanged(object sender, EventArgs e)
        {
            IntSelInd = LbSongs.SelectedIndex;

            LblThisWeek.Text = ListSongs[IntSelInd].LastWeekRank;
            LblMostWeek.Text = ListSongs[IntSelInd].MostWeekRank;
            LblLastWeek.Text = ListSongs[IntSelInd].LastWeekRank;
            LblArtist.Text = ListSongs[IntSelInd].NameOfArtist;

            BTF(IntSelInd);

            axWindowsMediaPlayer1.URL = @ListSongs[IntSelInd].NameOfFile;
        }

Timer (Add [timer1.Start();] In Frm Load)

DateTime datetime = DateTime.Now;
        this.LblTime.Text = datetime.ToString();
Dave
  • 1
  • 1