[英]Creating a recurring timer
我的任务是创建一个C#SDK的Java版本。 目前。 我正在开发一个扩展C#System.ServiceProcess.ServiceBase的类,但是由于在Java中创建Windows服务的困难,我正专注于该类中的一些其他方法。
我试图在Java中复制的当前C#方法如下所示
private void StartProcesses()
{
// create a new cancellationtoken souce
_cts = new CancellationTokenSource();
// start the window timer
_windowTimer = new Timer(new TimerCallback(WindowCallback),
_cts.Token, 0, Convert.ToInt64(this.SQSWindow.TotalMilliseconds));
this.IsWindowing = true;
}
在分析了这部分代码后,我相信它初始化了一个System.threading.Timer对象,该对象每隔SQSWindow毫秒执行一次WindowCallback函数。
阅读了java.util.concurrent文档
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/package-summary.html
我不确定如何在Java中复制C#功能,因为我找不到与Timer功能相同的功能。 Java库提供的TimeUnit似乎仅用于线程超时,而不是发出重复操作。
我也很好奇使用CancellationTokenSource。 如果要查询此对象以确定是否要继续操作,为什么它不是一个灵长类动物,如布尔值? 它提供了哪些附加功能,Java的多线程模型中是否有类似的结构?
使用ScheduledThreadPoolExecutor
,您可以获得非常类似的功能:
ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
Runnable task = new Runnable() {
public void run() {
//here the code that needs to run periodically
}
};
//run the task every 200 ms from now
Future<?> future = scheduler.scheduleAtFixedRate(task, 0, 200, TimeUnit.MILLISECONDS);
//a bit later, you want to cancel the scheduled task:
future.cancel(true);
您可能想要查看ScheduledThreadPoolExecutor 。 它是ScheduledExecutorService的一个实现,它具有定期调度的能力。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.