每分钟使MyFunction()触发

问题描述 投票:-2回答:2

我有这个C#代码,我想让它每分钟触发一次。

private void MyFunction()
{
    if (DateTime.Now.Hour == 6 && ranalarm == false)
    {
        ranalarm = true;
        Event();
    }
    else if (DateTime.Now.Hour != 6 && ranalarm == true)
    {
        ranalarm = false;
    }
}

如何在C#中每分钟触发函数MyFunction()?我尝试与计时器合作,但Visual Studio说它与我的System.Windows.Forms冲突。

c# .net timer
2个回答
3
投票

你可以使用System.Threading.TimerTimeSpan。像这样的东西:

TimeSpan start = TimeSpan.Zero;
TimeSpan minutes = TimeSpan.FromMinutes(1);

var timer = new System.Threading.Timer(c =>
{
    MyFunction();
}, null, start, minutes);

1
投票

这是我的解决方案。没有使用线程。简单易行,但完成工作

Timer testTimer;

public void initTimer()
{
    testTimer = new Timer();
    testTimer.Tick += testTimer_tick ;
    testTimer.Interval = 1000; //timer interval in mili seconds;
    testTimer.Start();
}

public void testTimer_tick(object sender, EventArgs e)
{           
    MyFunction(); // your function comes here           
}

你可以复制它并粘贴。接下来只需在表单加载事件中调用initTimer()方法。

© www.soinside.com 2019 - 2024. All rights reserved.