如何在Java独立运行计时器?

发布于 2025-02-07 16:47:24 字数 2229 浏览 2 评论 0原文

我正在尝试为每个人构建多个计时器和计划的独立任务。我有一个用于持有计时器及其变量的构造函数。然后,我将它们称为一个一个,但我发现传递给计时器构造器的变量彼此叠加。我已经将每个计时器作为新实例启动,但仍无法解决问题。如何确保计时器独立运行?

代码:

public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        TimerTrigger.INSTANCE.runTimer();
    }
}

触发计时器:

public enum TimerTrigger {
    INSTANCE;

    private TimerTrigger(){}

    public void runTimer(){
      for (int i = 0; i < 3; i++) {
        System.out.println( "Initiaizing Timer " + i );
        TimerConstructor tmpTimer = new TimerConstructor();
        varObjectvo timerVariable = new varObjectvo();
        timerVariable.setIndex(i);
        // timerList.add(tmpTimer); 
        tmpTimer.start(timerVariable); //timerVariable is a value object
      }
    }
}

计时器的构造函数:

import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
public class TimerConstructor{
    private static varObjectvo timerVO = null;
    Timer timer = null; 
  
    public void start(varObjectvo obj) {
      timer = new Timer("Timer_" + obj.getIndex()); // will be Timer_1/2/3
      timerVO = obj;
      TimerChecker task = new TimerChecker();
      timer.scheduleAtFixedRate(task, new Date(), 10000);
    }
  
    private class TimerChecker extends TimerTask {
      public void run() {
        System.out.println("It is timer " + timerVO.getIndex() + " from: " + timer.toString());
      }
    }
  }

值对象类:

public class varObjectvo{
    private Integer index;
    
    public void setIndex(Integer i){ 
        this.index = i;
    };

    public Integer getIndex(){ 
        return this.index;
    };
  }

输出:

Hello World!
Initiaizing Timer 0
Initiaizing Timer 1
It is timer 0 from:java.util.Timer@6b45c377
It is timer 1 from:java.util.Timer@17481b7c
Initiaizing Timer 2
It is timer 2 from:java.util.Timer@48e94d09
It is timer 2 from:java.util.Timer@17481b7c
It is timer 2 from:java.util.Timer@48e94d09
It is timer 2 from:java.util.Timer@6b45c377

简而言之,似乎以前的计时器中的变量被以后的Timer覆盖。

I am trying to build multiple Timers and scheduled independent tasks for each of them. I have a constructor for holding a Timer and its variable. Then, I will call them one by one but I found that the variables, passed to the Timer constructor, are overrode by each other. I already initiate each Timer as a new instance but still cannot solve the issue. How can I make sure the timers are run independently?

Code:

public class App 
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        TimerTrigger.INSTANCE.runTimer();
    }
}

To Trigger the timer:

public enum TimerTrigger {
    INSTANCE;

    private TimerTrigger(){}

    public void runTimer(){
      for (int i = 0; i < 3; i++) {
        System.out.println( "Initiaizing Timer " + i );
        TimerConstructor tmpTimer = new TimerConstructor();
        varObjectvo timerVariable = new varObjectvo();
        timerVariable.setIndex(i);
        // timerList.add(tmpTimer); 
        tmpTimer.start(timerVariable); //timerVariable is a value object
      }
    }
}

The Constructor of timer:

import java.util.Timer;
import java.util.TimerTask;
import java.util.Date;
public class TimerConstructor{
    private static varObjectvo timerVO = null;
    Timer timer = null; 
  
    public void start(varObjectvo obj) {
      timer = new Timer("Timer_" + obj.getIndex()); // will be Timer_1/2/3
      timerVO = obj;
      TimerChecker task = new TimerChecker();
      timer.scheduleAtFixedRate(task, new Date(), 10000);
    }
  
    private class TimerChecker extends TimerTask {
      public void run() {
        System.out.println("It is timer " + timerVO.getIndex() + " from: " + timer.toString());
      }
    }
  }

The value object class:

public class varObjectvo{
    private Integer index;
    
    public void setIndex(Integer i){ 
        this.index = i;
    };

    public Integer getIndex(){ 
        return this.index;
    };
  }

Output:

Hello World!
Initiaizing Timer 0
Initiaizing Timer 1
It is timer 0 from:java.util.Timer@6b45c377
It is timer 1 from:java.util.Timer@17481b7c
Initiaizing Timer 2
It is timer 2 from:java.util.Timer@48e94d09
It is timer 2 from:java.util.Timer@17481b7c
It is timer 2 from:java.util.Timer@48e94d09
It is timer 2 from:java.util.Timer@6b45c377

In short, seems the variables in former Timer are being overwritten by the later Timer.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦言归人 2025-02-14 16:47:24

如注释,您的主要问题似乎是使您的变量Timervo static

static关键字意味着您只需要一个这样的值,而不是每个实例具有该名称已知的值。换句话说,static不是面向对象的。

因此,每次执行timervo = obj;时,都将先前存储的值替换为当前一个值。您在整个应用程序中只有一个timervo,因为您将其标记为static。该Timervo只能包含一个值,即最后分配的值。

你说:

我已经将每个计时器启动为新实例,但仍无法解决问题。

但是…您实例化的所有计时器对象共享相同的单个static timervo对象。


小问题:班级名称以大写字母开头。因此,公共类VarobjectVo应为公共类VarobjectVo

另一个小问题:命名方法“…构造者”令人困惑。该词在Java中具有非常具体的关键含义。 Java中的构造函数始终与班级名称相同。

更大的图片:您没有利用现代爪哇。如果您仔细阅读计时器timertask类的Javadoc,您会发现它们是多年前由执行者框架取代的。

要使用执行者,请定义您的任务为实现运行callable。然后建立一个scheduledexecutorservice。将任务的实例提交到该服务中,以重复执行。

搜索堆栈溢出以了解更多信息。预定的执行者服务已经涵盖了很多次。

以下是一些粗糙的未经测试的代码。

class Counter implements Runnable {
    private final AtomicInteger count = new AtomicInteger( 0 ) ;

    void run() { this.count.incrementAndGet() ; }

    int getCount() { return this.count.get() ; }
}

实例。

Counter countEvery5Seconds = new Counter() ;
Counter countEvery42Seconds = new Counter() ;

初始化您的计划执行人服务。

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ; 

安排您的任务。

ScheduledFuture<?> count5 =
   scheduler.scheduleAtFixedRate( countEvery5Seconds, 0, 5, TimeUnit.SECONDS);
ScheduledFuture<?> count42 =
   scheduler.scheduleAtFixedRate( countEvery42Seconds, 0, 42, TimeUnit.SECONDS);

确保关闭执行人服务。请参阅许多其他答案中的讨论。请参阅Javadoc中的样板代码。

As commented, your main problem seems to be making your variable timerVO static.

The static keyword means you want only one such value rather than each instance having its own value known by that name. In other words, static is not object-oriented.

So each time you execute timerVO = obj;, you replace the previously stored value with the current one. You have only a single timerVO in your entire app, because you marked it static. That timerVO can contain only a single value, the value last assigned.

You said:

I already initiate each timer as new instance but still cannot solve the issue.

But… all those timer objects you instantiated share the same single static timerVO object.


Minor issue: Class names start with an uppercase letter. So public class varObjectvo should be public class VarObjectvo.

Another minor issue: Naming a method “…Constructor” is confusing. That word has a very specific crucial meaning in Java. A constructor in Java is always named the same as the class name.

Bigger picture: You are not taking advantage of modern Java. If you read carefully the Javadoc of Timer and TimerTask classes, you’ll see they were supplanted years ago by the Executors framework.

To use executors, define your tasks as implementing either Runnable or Callable. Then establish a ScheduledExecutorService. Submit instances of your tasks to that service for repeated execution.

Search Stack Overflow to learn more. Scheduled executor service has been covered many many times already.

Some rough untested code follows.

class Counter implements Runnable {
    private final AtomicInteger count = new AtomicInteger( 0 ) ;

    void run() { this.count.incrementAndGet() ; }

    int getCount() { return this.count.get() ; }
}

Instantiate.

Counter countEvery5Seconds = new Counter() ;
Counter countEvery42Seconds = new Counter() ;

Initialize your scheduled executor service.

ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor() ; 

Schedule your tasks.

ScheduledFuture<?> count5 =
   scheduler.scheduleAtFixedRate( countEvery5Seconds, 0, 5, TimeUnit.SECONDS);
ScheduledFuture<?> count42 =
   scheduler.scheduleAtFixedRate( countEvery42Seconds, 0, 42, TimeUnit.SECONDS);

Be sure to shutdown your executor service. See discussions in many other Answers. See boilerplate code in Javadoc.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文