创建定期计时器

时间:2013-06-07 19:18:01

标签: c# java multithreading

我的任务是创建一个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的多线程模型中是否有类似的结构?

3 个答案:

答案 0 :(得分:2)

使用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);

答案 1 :(得分:1)

等效的Java类是“TimerTimerTask

示例:

Timer t = new Timer();
t.schedule(new TimerTask(){

    @Override
    public void run() {
        // Do stuff
    }

}, startTime, repeatEvery);

如果您希望取消,请使用TimerTask作为变量。 TimerTask类的方法为cancel

答案 2 :(得分:1)

您可能需要查看ScheduledThreadPoolExecutor。它是ScheduledExecutorService的一种实现,可以定期安排。