简体   繁体   English

TimerTask 类必须在 Java 中只运行一次

[英]TimerTask class has to run only once in java

I have a class that runs for every 10 secs, but when I execute it more than once, multiple timers are started.我有一个每 10 秒运行一次的类,但是当我多次执行它时,会启动多个计时器。 If one timer is already running, I want the other timer calls to be ignored.如果一个计时器已经在运行,我希望其他计时器调用被忽略。 I want only one timer to be running at a given point of time.我只想在给定的时间点运行一个计时器。 Please help.请帮忙。

My code:我的代码:

import java.util.Timer;
import java.util.TimerTask;
public class Test1 extends TimerTask{
    @Override
    public void run() {
            System.out.println("In run method");
        }

    public static void main(String args[]) {
        System.out.println("In main method");
        Timer timer= new Timer();
        timer.schedule(new Test1(), 10000,10000);
    }
}

I want the 1st timer to be running always.我希望第一个计时器始终运行。 Other timers calls should not be triggered at all.根本不应触发其他计时器调用。

Try with Singleton patten that allows only single instance of the class.尝试使用只允许类的单个实例的Singleton 模式

Sample code:示例代码:

public class Test extends TimerTask {    
    private static Test instance = new Test();

    private Test() {}    
    public static Test getInstance() {
        return instance;
    }

    @Override
    public void run() {
        System.out.println("In run method");
    }
}

Now if you try to start another Task on the same instance it will result in below exception:现在,如果您尝试在同一实例上启动另一个任务,则会导致以下异常:

java.lang.IllegalStateException: Task already scheduled or cancelled
at java.util.Timer.sched(Unknown Source)
at java.util.Timer.schedule(Unknown Source)

Why don't you try something like setting a bool true if you start a timer and only let the other Timers start if it's true or false, depends on how you set them如果您启动一个计时器,为什么不尝试设置 bool true 之类的事情,并且只让其他计时器启动,如果它是真或假,取决于您如何设置它们

sth like:喜欢:

boolean checkTimer = false;

//Start a Timer and set checkTimer = true

if(checkTimer == true)
{
  //Start your other timers here
}
else
{
  //Write message that timer is already running
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM