如何在计时器上运行C#方法?我在网上找到了这个例子,但下面的DoStuffOnTimer()方法没有被点击:
model_id <- str_extract(unique_strings, "[0-9]{4,}")
unique(model_id)
[1] "5003" "7003"
答案 0 :(得分:1)
或者,如果您不需要非常精确的计时器,您可以自己创建它:
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Temp
{
internal class Program
{
// this is the `Timer`
private static async Task CallWithInterval(Action action, TimeSpan interval, CancellationToken token)
{
while (true)
{
await Task.Delay(interval, token);
if (token.IsCancellationRequested)
{
return;
}
action();
}
}
// your method which is called with some interval
private static void DoSomething()
{
Console.WriteLine("ding!");
}
// usage sample
private static void Main()
{
// we need it to add the ability to stop timer on demand at any time
var cts = new CancellationTokenSource();
// start Timer
var task = CallWithInterval(DoSomething, TimeSpan.FromSeconds(1), cts.Token);
// continue doing another things - I stubbed it with Sleep
Thread.Sleep(5000);
// if you need to stop timer, let's try it!
cts.Cancel();
// check out, it really stopped!
Thread.Sleep(2000);
}
}
}
答案 1 :(得分:0)
using System;
using System.Timers;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Program thisone = new Program();
thisone.DoStuff();
Console.Read();
}
public void DoStuff()
{
var intervalMs = 5000;
Timer timer = new Timer(intervalMs);
timer.Elapsed += new ElapsedEventHandler(DoStuffOnTimer);
timer.Enabled = true;
}
private void DoStuffOnTimer(object source, ElapsedEventArgs e)
{
//do stuff
Console.WriteLine("Tick!");
}
}
}