Make MyFunction() trigger every minute

独自空忆成欢 提交于 2021-02-07 11:11:08

问题


I have this C# code and I want it to trigger every minute.

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

How can I make function MyFunction() trigger every minute in C#? I tried working with timers but Visual Studio said it conflicted with my System.Windows.Forms.


回答1:


You can use System.Threading.Timer and TimeSpan. Something like this:

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

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



回答2:


This is my solution. No use of threading. Simple easy but gets the job done

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           
}

You can just copy this and paste. Next just call the initTimer() method in form load event.



来源:https://stackoverflow.com/questions/52800843/make-myfunction-trigger-every-minute

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!