问题
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