C# 创建一个每 30 分钟运行一次代码的计时器循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16241435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:31:01  来源:igfitidea点击:

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

c#visual-studio.net-4.0timerautosave

提问by Toby

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.

我想在我的 C# 程序中输入一个自动保存功能,它将在倒计时结束时运行一行代码,然后重新启动倒计时。它将运行我的SaveFile();功能。

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.

我希望在用户第一次保存/打开文档时启动此计时器,并在他们打开新文档时禁用它。

回答by Hossein Narimani Rad

You can use System.Timers.Timer. It also has Stopand Startmethods so you can do whatever you want.

您可以使用System.Timers.Timer. 它还具有StopStart方法,因此您可以随心所欲。

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
}

回答by Pierre-Luc Pineault

You can use the Elapsed eventon the System.Timers Timer.

您可以在 System.Timers Timer上使用Elapsed 事件

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.

并且不要忘记在需要timer.Start()时打电话。

回答by Geoff Murtaugh

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

您也可以使用 DispatchTimer。这是每 5 分钟播放五个不同视频之一的片段。

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

回答by Dave

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

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

将字符转换为 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)

定时器(在Frm Load中添加[timer1.Start();])

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